Show the : character in the timezone offset using

2019-03-29 09:08发布

This question already has an answer here:

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条回答
倾城 Initia
2楼-- · 2019-03-29 09:41

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.

查看更多
登录 后发表回答