【问题标题】:Why is Python's weekday() different from tm_wday in C?为什么 Python 的 weekday() 与 C 中的 tm_wday 不同?
【发布时间】:2014-01-10 13:27:56
【问题描述】:

Python 文档将datetime.weekday() 定义为an integer, where Monday is 0 and Sunday is 6,而C 的tm.tm_wday 定义为days since Sunday。所以tm_wday就是(datetime.weekday() + 1) % 7,很不方便。鉴于 Python 通常坚持接近 C 等价物,为什么要这样做?

【问题讨论】:

  • FWIW,标准的星期日期编码 (ISO 8601) 指定星期从星期一开始
  • FWIW 我不认为 datetime 模块直接包装 C API 函数 1:1。我认为它更像是一个更高级别的模块。
  • @JamesMills:但time 模块确实,它使用相同的约定(参见docs.python.org/2/library/time.html#time.struct_time)。
  • @MartijnPieters 当然是的 :) 但是我认为您无法访问某些内部 C 结构?除非你使用 ctypes 或 cffi。
  • 我注意到 Python time 模块对 C struct_tm 约定进行了更多更改。月份数字是 1 到 12,而不是 0 到 11。

标签: python c datetime


【解决方案1】:

这是 Guido van Rossum 在第一次为 Python 0.9.9 版本创建 time 模块时做出的明确决定; original commit 没有解释为什么他做出这个选择,但是使用 0 表示星期一从添加 localtimegmtime 函数的那一刻起就已成为 Python 的一部分。请参阅该早期版本中的time_convert() function

我们将不得不猜测他为什么这样做。最有可能的是,Guido 在工作日坚持使用 ISO 8601 约定而不是 C stdlib 约定,也许是因为他是欧洲人,而 Monday is the prevailing start if the week。另一种选择是他完全用另一种语言来模仿行为。 Python的根源是多种多样的,除了ABC,C和C++还包括Modula 3。不是后者使用这个约定;它follows the C stdlib instead

请注意,他还为 tm_mon 值使用了不同的范围,从 1 到 12,而不是使用 0 到 11 的 C stdlib 约定。

无论如何,question on comp.lang.python in 2000 about why time.gmtime() uses 0 for Monday 仍未得到答复。

【讨论】:

  • +1 用于挖掘 Python 源代码库的修订历史 :)
  • 可能他也只是看了墙上的日历。在大多数欧洲国家,每周从星期一开始
猜你喜欢
  • 2011-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-10
  • 1970-01-01
  • 2023-04-09
  • 2013-03-22
  • 1970-01-01
相关资源
最近更新 更多