gpt4 book ai didi

python - 如何用python解析包含毫秒的时间字符串?

转载 作者:太空宇宙 更新时间:2023-11-03 20:40:46 24 4
gpt4 key购买 nike

我能够使用 time.strptime 解析包含日期/时间的字符串

>>> import time
>>> time.strptime('30/03/09 16:31:32', '%d/%m/%y %H:%M:%S')
(2009, 3, 30, 16, 31, 32, 0, 89, -1)

如何解析包含毫秒的时间字符串?

>>> time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.5/_strptime.py", line 333, in strptime
data_string[found.end():])
ValueError: unconverted data remains: .123

最佳答案

Python 2.6 添加了新的 strftime/strptime 宏 %f。这些文档有点误导,因为它们只提到微秒,但 %f 实际上解析任何秒的小数部分,最多 6 位数字,这意味着它也适用于毫秒甚至厘秒或十分之一秒。

time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')

但是,time.struct_time实际上并不存储毫秒/微秒。您最好使用datetime,如下所示:

>>> from datetime import datetime
>>> a = datetime.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')
>>> a.microsecond
123000

如您所见,.123 被正确解释为 123 000 微秒。

关于python - 如何用python解析包含毫秒的时间字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56877933/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com