美文网首页python技巧
python datetime模块计算上周任意一天的日期

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

作者: 陆_志东 | 来源:发表于2018-07-24 00:27 被阅读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

相关文章

网友评论

    本文标题:python datetime模块计算上周任意一天的日期

    本文链接:https://www.haomeiwen.com/subject/ajusmftx.html