Find Monday's date with Python

前端 未结 8 1998
被撕碎了的回忆
被撕碎了的回忆 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:59

    ChristopheD's post is close to what you want. I don't have enough rep to make a comment :(

    Instead of (which actually gives you the next upcoming monday):

    >>> today + datetime.timedelta(days=-today.weekday(), weeks=1)
    datetime.date(2009, 10, 26)
    

    I would say:

    >>> last_monday = today - datetime.timedelta(days=today.weekday())
    

    If you want the previous week, add the 'weeks=1' parameter.

    This makes the code more readable since you are subtracting a timedelta. This clears up any confusion caused by adding a timedelta that has negative and positive offsets.

提交回复
热议问题