首页 > 解决方案 > 我应该在 Python 中使用 strptime 这个时间戳使用什么格式代码?

问题描述

我有一个 .txt 文件,其中包含字符串"2020-08-13T20:41:15.4227628Z" What format code 我应该strptime在 Python 3.7 的函数中使用什么格式?我尝试了以下方法,但'8'之前的结尾'Z'不是有效的工作日

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'

标签: pythondatetimestrptime

解决方案


后面的 7 位数字.似乎是纳秒数。您可以使用特定于平台的格式(由 定义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')

推荐阅读