在 Python 中使用 strptime 的时间戳应该使用什么格式代码?
What format code should I use for this timestamp with strptime in Python?
我有一个包含字符串 "2020-08-13T20:41:15.4227628Z"
的 .txt 文件
Python 3.7 中的 strptime
函数应该使用什么格式的代码?我尝试了以下操作,但 'Z'
之前的 '8'
不是有效的工作日
from datetime import datetime
timestamp_str = "2020-08-13T20:41:15.4227628Z"
timestamp = datetime.strptime(timestamp_str, '%Y-%m-%dT%H:%M:%S.%f%uZ')
ValueError: time data '2020-08-13T20:41:15.4227628Z' does not match format '%Y-%m-%dT%H:%M:%S.%f%uZ'
.
后面的 7 位数字似乎是纳秒数。您可能有 platform-specific 格式(由 strftime(3)
定义)可用于代替 %f
,但如果没有,最好的办法是在尝试解析剩余数字之前删除尾随数字字符串作为时间戳。
regex = "(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}).(\d.*)"
if (m := re.match(regex, timestamp_str) is not None:
timestamp_str = "".join(m.groups())
timestamp = datetime.strptime(timestamp_str, '%Y-%m-%dT%H:%M:%S.%fZ')
除了 7 位小数秒之外,您的时间戳格式大部分符合 ISO 8601。
- 第7位是1/10微秒;通常你会有 3、6 或 9 位分辨率(分别为毫秒、微秒或纳秒)。
- 其中Z表示UTC
在Python中可以方便的解析这种格式.
我有一个包含字符串 "2020-08-13T20:41:15.4227628Z"
的 .txt 文件
Python 3.7 中的 strptime
函数应该使用什么格式的代码?我尝试了以下操作,但 'Z'
之前的 '8'
不是有效的工作日
from datetime import datetime
timestamp_str = "2020-08-13T20:41:15.4227628Z"
timestamp = datetime.strptime(timestamp_str, '%Y-%m-%dT%H:%M:%S.%f%uZ')
ValueError: time data '2020-08-13T20:41:15.4227628Z' does not match format '%Y-%m-%dT%H:%M:%S.%f%uZ'
.
后面的 7 位数字似乎是纳秒数。您可能有 platform-specific 格式(由 strftime(3)
定义)可用于代替 %f
,但如果没有,最好的办法是在尝试解析剩余数字之前删除尾随数字字符串作为时间戳。
regex = "(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}).(\d.*)"
if (m := re.match(regex, timestamp_str) is not None:
timestamp_str = "".join(m.groups())
timestamp = datetime.strptime(timestamp_str, '%Y-%m-%dT%H:%M:%S.%fZ')
除了 7 位小数秒之外,您的时间戳格式大部分符合 ISO 8601。
- 第7位是1/10微秒;通常你会有 3、6 或 9 位分辨率(分别为毫秒、微秒或纳秒)。
- 其中Z表示UTC
在Python中可以方便的解析这种格式