Why do Python's datetime.strftime('%w') and datetime.weekday() use different indexes for the days of the week?

前端 未结 3 2057
梦毁少年i
梦毁少年i 2021-02-02 12:47

In Python, showing the day of the week as an integer using datetime.strftime() shows a different result than using datetime.weekday().

         


        
相关标签:
3条回答
  • 2021-02-02 12:53

    Maybe weekday is based on locale while strftime is not? Because I have different output:

    In [14]: d.strftime("%A")
    Out[14]: 'Sunday'
    
    In [15]: d.strftime("%w")
    Out[15]: '0'
    
    In [16]: now.weekday()
    Out[16]: 0
    
    0 讨论(0)
  • 2021-02-02 12:56

    Python's strftime function emulates that in the c library. Thus, the motivation that %w returns 0 for a Sunday comes entirely from that.

    In contrast, the method date.weekday() returns a 6 for Sunday as it seeks to match the behaviour of the much older time module. Within that module times are generally represented by a struct_time and within this, struct_time.tm_day uses a 6 to represent a Sunday.

    The correct question then becomes ... why does time.struct_time represent a Sunday as a 6, when the C library's tm struct uses a 0 ??

    And the answer is ... because it just does. This behaviour has existed ever since Guido first checked in gmtime and localtime functions in 1993.

    And Guido cannot be wrong ... so you best ask him.

    0 讨论(0)
  • 2021-02-02 13:08

    Originally, the ISO 8601 standard used 1 .. 7 to represent Monday through Sunday. For convenience, later on the interpretation 0=Sunday was permitted.

    If you want to use something that is more consistent, try using isoweekday

    The 0=Monday standard is the European convention. I guess that's no surprise :P

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