使用datetime.strftime在时区偏移中显示:字符

编程入门 行业动态 更新时间:2024-10-28 18:35:22
本文介绍了使用datetime.strftime在时区偏移中显示:字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

要赋予 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在时区偏移中显示:字符

本文发布于:2023-10-24 10:00:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1523649.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时区   字符   datetime   strftime

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!