How do I get the day of week given a date?

前端 未结 26 1775
迷失自我
迷失自我 2020-11-22 04:40

I want to find out the following: given a date (datetime object), what is the corresponding day of the week?

For instance, Sunday is the first day, Mond

26条回答
  •  故里飘歌
    2020-11-22 05:14

    To get Sunday as 1 through Saturday as 7, this is the simplest solution to your question:

    datetime.date.today().toordinal()%7 + 1
    

    All of them:

    import datetime
    
    today = datetime.date.today()
    sunday = today - datetime.timedelta(today.weekday()+1)
    
    for i in range(7):
        tmp_date = sunday + datetime.timedelta(i)
        print tmp_date.toordinal()%7 + 1, '==', tmp_date.strftime('%A')
    

    Output:

    1 == Sunday
    2 == Monday
    3 == Tuesday
    4 == Wednesday
    5 == Thursday
    6 == Friday
    7 == Saturday
    

提交回复
热议问题