【问题标题】:Show the : character in the timezone offset using datetime.strftime [duplicate]使用 datetime.strftime 在时区偏移中显示 : 字符 [重复]
【发布时间】:2014-07-19 00:23:55
【问题描述】:

提供给strftime 的格式字符串是什么,它将提供与isoformat(' ') 相同的输出?

>>> from datetime import datetime
>>> import pytz 
>>> dt = datetime.now(tz=pytz.UTC).replace(microsecond=0)
>>> print dt
2014-05-29 13:11:00+00:00
>>> dt.isoformat(' ')
'2014-05-29 13:11:00+00:00'
>>> dt.strftime('%Y-%m-%d %H:%M:%S%z')
'2014-05-29 13:11:00+0000'

日期时间的__str__ 行为是从哪里获得偏移量中的额外冒号的?我查看了formatting options,只能分别找到 +HHMM 或名称的 %z 和 %Z 。

我查看了datetime.__str__ 的实现,但没有得到任何提示,它只是说pass(?!)。我认为它最终会委托给isoformat(' '),但我不明白它是如何/在哪里实现的。

【问题讨论】:

    标签: python datetime timezone timezone-offset


    【解决方案1】:

    Datetime 是用 C 语言实现的。在那里你会发现 Pythons str 默认使用的tp_str 的函数只调用了isoformat()

    进一步datetime.strftime方法调用libc的strftime函数,它给出了不带分隔符的时区差异,而datetime.isoformat调用了一个方法,该方法直接为Python实现,其中可以传递分隔符,即在这种情况下是冒号。

    【讨论】:

      猜你喜欢
      • 2013-01-21
      • 1970-01-01
      • 2014-11-27
      • 2020-02-14
      • 1970-01-01
      • 2019-06-30
      • 1970-01-01
      • 2010-09-18
      • 1970-01-01
      相关资源
      最近更新 更多