python datetime模块计算上周任意一天的日期

from datetime import datetime
weekdays = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]

def get_previous_byday(dayname,start_date=None):
    if start_date is None:
        start_date = datetime.today()
    day_num = start_date.weekday()
    day_num_target = weekdays.index(dayname)
    days_ago = (7 + day_num -day_num_target) % 7   # 这里括号里面加7 是因为防止days_ago 出现负值
    if days_ag0 == 0:
        days_ago = 7
    target_date = start_date - datedelta(days=days_ago)
    return target_date

你可能感兴趣的:(python datetime模块计算上周任意一天的日期)