要赋予 strftime 的格式字符串是什么,其输出将与我看到的 isoformat('')?
>>从datetime导入datetime >>导入pytz >> dt = datetime.now(tz = pytz.UTC).replace(microsecond = 0)>>打印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 __ 行为在哪里得到偏移量中的多余冒号?我查看了格式化选项,并且只能分别为+ HHMM或名称找到%z和%Z。
我查看了 datetime的实现。__str __ ,但没有任何提示,只是说了通过(?!)。我认为它最终会委托给 isoformat(’),但我不知道该如何实现/在何处实现。
解决方案Datetime在C中实现。在那里您发现 tp_str ,默认情况下由Python str 使用,仅调用 isoformat()。
datetime.strftime 方法还调用libc strftime 函数,该函数没有分隔符的时区差异,而 datetime.isoformat 调用一个方法,该方法直接为Python实现,可以传递分隔符,在这种情况下为冒号。 / p>
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.
解决方案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.
更多推荐
使用datetime.strftime在时区偏移中显示:字符
发布评论