Show the : character in the timezone offset using datetime.strftime [duplicate]

懵懂的女人 提交于 2019-12-21 17:49:06

问题


What is the format string to give to strftime which would give the same output as I see for 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'

Where does the __str__ behaviour of datetime get that extra colon in the offset from? I looked in the formatting options and could only find %z and %Z for +HHMM or name respectively.

I looked at the implementation of datetime.__str__ but got no hints, it just says pass (?!). I think it eventually delegates to isoformat(' ') but I don't understand how/where that is implemented.


回答1:


Datetime is implemented in C. There you find that the function for tp_str, which is used by Pythons str by default, just calls isoformat().

Further the datetime.strftime method calls the libc strftime function, which gives the timezone difference without a seperator, whereas datetime.isoformat calls a method, which is implemented for Python directly, where a separator can be passed, which is the colon in this case.



来源:https://stackoverflow.com/questions/23934319/show-the-character-in-the-timezone-offset-using-datetime-strftime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!