How to parse str(my_datetime) using strptime?(如何使用 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) 被记录为等同于 d.isoformat(' ').这以 %Y-%m-%d %H:%M:%S (2017-01-01 00:00:00) 开头,然后:
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)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 strptime 解析 str(my_datetime)?
基础教程推荐
- Discord.py 缺少必需的参数 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
