How to get last Friday?

后端 未结 6 2269
南方客
南方客 2020-12-10 04:20

The code below should return last Friday, 16:00:00. But it returns Friday of previous week. How to fix that?

now = datetime.datetime.now()
test = (now - date         


        
6条回答
  •  抹茶落季
    2020-12-10 04:40

    The principle is the same as in your other question.

    Get the friday of the current week and, if we are later, subtract one week.

    import datetime
    from datetime import timedelta
    now = datetime.datetime.now()
    today = now.replace(hour=16,minute=0,second=0,microsecond=0)
    sow = (today - datetime.timedelta(days=now.weekday()))
    this_friday = sow + timedelta(days=4)
    if now > this_friday:
         test = this_friday
    else:
         test = this_friday + timedelta(weeks=-1)
    

提交回复
热议问题