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

我可以使用 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 实际上解析 any 秒的小数部分,最多 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 微秒。

https://stackoverflow.com/questions/698223/

相关文章:

python - 在python中将 float 转换为整数的最安全方法?

python - 找出 Python 中的对象正在使用多少内存

python - Google 大量使用 Python

linux - 如何使用 Bash 脚本自动添加用户帐户和密码?

python - 如何在 Flask-SQLAlchemy 应用程序中执行原始 SQL

linux - Bash 脚本并行处理有限数量的命令

linux - 如何规范化 Bash 中的文件路径?

linux - 如何获取进程 ID 以杀死 nohup 进程?

python - 如何从文件中读取特定行(按行号)?

linux - bash 中是否有 "goto"语句?