使用pytz与datetime时strptime和strftime转换时间出现差异的原因及解决方法
时间戳转换后出现时区偏移的问题解决
问题场景
执行以下代码时,original_value.timestamp()与转换后的new_value理论上应相等,但实际存在接近本地时区偏移的时间差(示例中差值为-19800秒):
original_value = (datetime.datetime.now(pytz.utc)) + datetime.timedelta(minutes=30) current_schedule = original_value.strftime("%Y-%m-%dT%H:%M:%S.%fZ") new_value = datetime.datetime.strptime(current_schedule,"%Y-%m-%dT%H:%M:%S.%fZ").timestamp()
完整测试代码:
import datetime import pytz ab = (datetime.datetime.now(pytz.utc)) + datetime.timedelta(minutes=30) current_schedule = ab.strftime("%Y-%m-%dT%H:%M:%S.%fZ") new_time = datetime.datetime.strptime(current_schedule,"%Y-%m-%dT%H:%M:%S.%fZ").timestamp() print("Value Initially: {}".format(ab.timestamp())) print("Value post converstion: {}".format(new_time)) time_diff = new_time - ab.timestamp() print(time_diff)
输出示例:
Value Initially: 1680806908.778667 Value post converstion: 1680787108.778667 -19800.0
疑问:为何转换前后时间戳不一致?如何让差值始终为0?
问题原因
strptime解析生成的是无时区感知(naive)的datetime对象,调用timestamp()时,Python会将其视为本地时区的时间进行转换;而原original_value是带UTC时区信息的datetime对象,两者时区基准不同,导致时间戳出现偏移。
解决方法
解析后为datetime对象指定UTC时区,再调用timestamp()即可解决:
方法一:使用replace指定时区
# 解析后为对象添加UTC时区信息 new_time_obj = datetime.datetime.strptime(current_schedule, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=pytz.utc) new_time = new_time_obj.timestamp()
方法二(Python3.7+):使用fromisoformat简化操作
# 将Z替换为+00:00,适配fromisoformat的格式要求 new_time_obj = datetime.datetime.fromisoformat(current_schedule.replace('Z', '+00:00')) new_time = new_time_obj.timestamp()
修改后,转换前后的时间戳将完全一致。
内容的提问来源于stack exchange,提问作者Devarshi Singh
相关产品推荐
相关产品推荐

