python技巧

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

2018-07-24  本文已影响0人  陆_志东
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
上一篇下一篇

猜你喜欢

热点阅读