How to get last Friday?

后端 未结 6 2278
南方客
南方客 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条回答
  •  猫巷女王i
    2020-12-10 04:46

    Could be lame but to me simplest. Get the last day of the current month and start checking in a loop (which wouldn't cost anything since max loops before finding last friday is 7) for friday. if last day is not friday decrement and the check the day before.

    import calendar
    from datetime import datetime, date
    
    def main():
        year = datetime.today().year    
        month = datetime.today().month  
        x = calendar.monthrange(year,month)
        lastday = x[1]
        while True:
            z = calendar.weekday(year, month, lastday)
            if z != 4:
                lastday -= 1
            else:
                print(date(year,month,lastday))
                break
    
    if __name__ == "__main__":
        main()
    

提交回复
热议问题