You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中计算ISO 8601格式时间戳的差值?

解决ISO 8601时间戳格式不匹配问题

嘿,这个问题我之前处理过,咱们先搞清楚错误根源:你的时间戳是标准ISO 8601格式2022-04-20T05:42:05Z,但你写的格式字符串'%Y-%m-%d %H:%M:%S:%fZ'有两个明显的不匹配点:

  • 日期和时间之间的分隔符是T,但你用了空格
  • 你的时间戳没有微秒部分(也就是:05后面没有.xxxxxx),但格式里加了%f

针对这个问题,有两种简单的解决办法:

方法1:修正格式字符串

直接把格式字符串改成和输入完全匹配的样子,去掉多余的%f,把空格换成T:

from datetime import datetime

fmt = '%Y-%m-%dT%H:%M:%SZ'
first_timestamp = '2022-04-20T05:42:05Z'
second_timestamp = '2022-04-20T05:30:05Z'

tstamp1 = datetime.strptime(first_timestamp, fmt)
tstamp2 = datetime.strptime(second_timestamp, fmt)
td = tstamp1 - tstamp2
td_mins = int(round(td.total_seconds() / 60))
total_min = total_min + td_mins  # 记得先初始化total_min变量哦

方法2:用fromisoformat简化处理(Python 3.7+)

从Python 3.7开始,datetime模块提供了fromisoformat方法,能直接解析ISO 8601格式的时间戳,不用手动写格式字符串,更省心。不过要注意,这个方法默认不识别Z,所以可以先把Z替换成UTC偏移量+00:00:

from datetime import datetime

first_timestamp = '2022-04-20T05:42:05Z'
second_timestamp = '2022-04-20T05:30:05Z'

# 替换Z为UTC偏移量,确保正确解析UTC时间
tstamp1 = datetime.fromisoformat(first_timestamp.replace('Z', '+00:00'))
tstamp2 = datetime.fromisoformat(second_timestamp.replace('Z', '+00:00'))

td = tstamp1 - tstamp2
td_mins = int(round(td.total_seconds() / 60))
total_min = total_min + td_mins

如果你的时间戳偶尔会带微秒(比如2022-04-20T05:42:05.123Z),第二种方法会自动适配,不用修改代码,这也是它的一大优势~

内容的提问来源于stack exchange,提问作者D kashyap

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 18:02:40