python - 我应该在 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'
解决方案
后面的 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')
推荐阅读
- mysql - 不会写;模式更新时表中的重复键
- scala - Source.fromResource() 在测试期间不从 src/main/resources 读取文件
- python - Openpyxl没有将BeautifulSoup的多行输出写入单元格
- python - 尽管使用 end="",为什么输出包含新行
- java - 使用 Spring 的 TimeBasedRollingPolicy
- jakarta-ee - 处理声明默认 Web 模块的运行 Payara 5 的服务器意外关闭
- android - Android 上下文已弃用
- ruby-on-rails - 在 Rails 4 中带有 has_many 声明和没有其他参数的 :uniq 的弃用警告
- javascript - HTML 表格 - 如果列包含特定符号,则替换列中的值
- r - 从 github 下载和/或导入 R 数据