Find Monday's date with Python

前端 未结 8 2005
被撕碎了的回忆
被撕碎了的回忆 2020-12-13 03:22

How do I find the previous Monday\'s date, based off of the current date using Python? I thought maybe I could use: datetime.weekday() to do it, but I am gettin

8条回答
  •  温柔的废话
    2020-12-13 03:57

    For future googlers who show up on this page looking for a way to get "the most recent Sunday", rather than "the most recent Monday", you need to do some additional math because datetime.weekday() treats Monday as the first day of the week:

    today = datetime.date.today()
    weekday = today.weekday() + 1
    start_day = today - datetime.timedelta(days=weekday % 7)
    

    If today is Tuesday, this sets start_day to last Sunday. If today is Sunday, this sets start_day to today. Take away the % 7 if you want "last Sunday" to be a week ago if it's currently Sunday.

提交回复
热议问题