为什么Python的datetime.strftime('%w')和datetime.weekday()对周几使用不同的索引?
在Python中,使用 datetime.strftime()
来显示星期几的数字结果和使用 datetime.weekday()
的结果是不一样的。
>>> import datetime
>>> now = datetime.datetime.now()
>>> now.strftime('%A')
'Sunday'
>>> now.strftime('%w') # Day of the week as an integer.
'0'
>>> now.weekday() # Day of the week as an integer, a different way.
6
使用 strftime()
时,字符串格式 %w
把星期天当作一周的第一天。而使用 weekday()
时,星期一才是第一天。
这两者为什么会有这样的历史差异呢?
3 个回答
2
可能是因为weekday
这个函数是根据地区设置来决定的,而strftime
则不是?因为我得到了不同的输出:
In [14]: d.strftime("%A")
Out[14]: 'Sunday'
In [15]: d.strftime("%w")
Out[15]: '0'
In [16]: now.weekday()
Out[16]: 0
5
最开始,ISO 8601标准用 1 .. 7
来表示从星期一到星期天。为了方便,后来允许用 0=星期天
的方式来理解。
如果你想用一个更统一的方式,可以试试 isoweekday
。
0=星期一
这个标准是欧洲的习惯。我想这也不奇怪 :P
14
Python中的strftime
函数是模仿C语言库里的同名函数。因此,%w
返回0
表示星期天,完全是因为这个原因。
而date.weekday()
方法则返回6
表示星期天,因为它想要和更早的time
模块保持一致。在这个模块中,时间通常用struct_time
来表示,而在这个结构中,struct_time.tm_day
用6
来表示星期天。
所以,正确的问题是……为什么time.struct_time
用6
表示星期天,而C语言库的tm
结构却用0
呢?
答案是……因为就是这样。这种行为从1993年Guido第一次提交gmtime
和localtime
函数以来就一直存在。
而Guido是不会错的……所以你最好去问他。