Find Monday's date with Python

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

    Note: The OP says in the comments, "I was looking for the past Monday". I take this to mean we are looking for the last Monday that occurred strictly before today.

    The calculation is a little difficult to get right using only the datetime module (especially given the above interpretation of "past Monday" and if you wish to avoid clunky if-statements). For example, if today is a Monday such as 2013-12-23,

    today - DT.timedelta(days=today.weekday())
    

    returns 2013-12-23, which is the same day as today (not the past Monday).

    The advantage of using the dateutil module is that you don't have to do tricky mental calculations nor force the reader to do the same to get the right date. dateutil does it all for you:

    import dateutil.relativedelta as rdelta
    import datetime as DT
    
    today = DT.date(2013, 12, 23)  # Monday
    
    past_monday = today + rdelta.relativedelta(days=-1, weekday=rdelta.MO(-1))
    print(past_monday)
    # 2013-12-16
    
    next_monday = today + rdelta.relativedelta(days=1, weekday=rdelta.MO(+1))
    print(next_monday)
    # 2013-12-30
    

    Note that days=-1 is needed to guarantee that past_monday is a different day than today.

    0 讨论(0)
  • 2020-12-13 04:09
    d = datetime.datetime.today().weekday()
    

    gives you today's day of the week, counting 0 (monday) to 6 (sunday)

    datetime.datetime.today() + datetime.timedelta(days=(7-d)%7)
    

    (7-d)%7 gives you days until Monday, or leaves you where you are if today is Monday

    0 讨论(0)
提交回复
热议问题