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

前端 未结 26 1343
迷失自我
迷失自我 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
    
    0 讨论(0)
  • 2020-11-22 05:15

    use this code:

    import pandas as pd
    from datetime import datetime
    print(pd.DatetimeIndex(df['give_date']).day)
    
    0 讨论(0)
  • 2020-11-22 05:21

    This is a solution if the date is a datetime object.

    import datetime
    def dow(date):
        days=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
        dayNumber=date.weekday()
        print days[dayNumber]
    
    0 讨论(0)
  • 2020-11-22 05:22

    A simple, straightforward and still not mentioned option:

    import datetime
    ...
    givenDateObj = datetime.date(2017, 10, 20)
    weekday      = givenDateObj.isocalendar()[2] # 5
    weeknumber   = givenDateObj.isocalendar()[1] # 42
    
    0 讨论(0)
  • 2020-11-22 05:24

    Use date.weekday() or date.isoweekday().

    0 讨论(0)
  • 2020-11-22 05:24

    If you have reason to avoid the use of the datetime module, then this function will work.

    Note: The change from the Julian to the Gregorian calendar is assumed to have occurred in 1582. If this is not true for your calendar of interest then change the line if year > 1582: accordingly.

    def dow(year,month,day):
        """ day of week, Sunday = 1, Saturday = 7
         http://en.wikipedia.org/wiki/Zeller%27s_congruence """
        m, q = month, day
        if m == 1:
            m = 13
            year -= 1
        elif m == 2:
            m = 14
            year -= 1
        K = year % 100    
        J = year // 100
        f = (q + int(13*(m + 1)/5.0) + K + int(K/4.0))
        fg = f + int(J/4.0) - 2 * J
        fj = f + 5 - J
        if year > 1582:
            h = fg % 7
        else:
            h = fj % 7
        if h == 0:
            h = 7
        return h
    
    0 讨论(0)
提交回复
热议问题