如何使用strptime解析str(my_datetime)? [英] How to parse str(my_datetime) using strptime?

查看:68
本文介绍了如何使用strptime解析str(my_datetime)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是默认字符串表示形式日期时间:

>>> from datetime import datetime, timezone
>>> dt = datetime(2017, 1, 1, tzinfo=timezone.utc)
>>> print(dt)
2017-01-01 00:00:00+00:00

使用 datetime.strptime 解析的正确格式字符串是什么?就是说,什么格式代替了"???"?始终具有以下不变式:

What is the correct format string to parse that with datetime.strptime? That is, what format goes in place of the "???" to consistently have the following invariant:

>>> dt == datetime.strptime(str(dt), "???")
True

推荐答案

请注意,据记录 str(d)等效于

Note that str(d) is documented as being equivalent to d.isoformat(' '). This starts with %Y-%m-%d %H:%M:%S (2017-01-01 00:00:00), but then:

  • 什么都不是,或者.%f ,取决于微秒部分是否为非零.
  • 没有任何内容或没有像 + HH:MM 这样的偏移量,具体取决于实例是否支持时区.
  • Either has nothing or .%f, depending whether the microseconds part is nonzero.
  • Either has nothing or an offset like +HH:MM, depending whether the instance is timezone-aware.

datetime.strptime 不支持可选部分,因此没有一个单独的 format 参数可以匹配所有可能的输出.

datetime.strptime doesn't have support for optional parts, therefore there isn't a single format parameter that can match all of the possible outputs.

在Python 3.7+中,您可以使用 datetime.fromisoformat 解析 datetime.isoformat 输出.Paul Ganssle在 issue15873 中贡献.

In Python 3.7+, you can use datetime.fromisoformat to parse datetime.isoformat output. Contributed by Paul Ganssle in issue15873.

这篇关于如何使用strptime解析str(my_datetime)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆