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()
现在理论上
original_value.timestamp()
应该等于 new_value
变量,但是人们会注意到时差等于或至少接近他们的机器所在的时区。
对我来说大约是 17000 秒或 19000 秒,这也不一致。
如何始终如一地发现两者之间的差异为 0 秒,理想情况下应该如此。
我使用的功能:
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
请解释为什么会这样?后期时间应该与前期时间相同,因为它们只是从一个转换为另一个!
如何解决这个问题?
ab 有时间和时区数据,其中 new_time = datetime.datetime.strptime(current_schedule,"%Y-%m-%dT%H:%M:%S.%fZ") 将没有时区详细信息使其在调用时间戳方法时使用您当地的时区作为参考。因此,ab.timestamp() 将使用 UTC,而值 new_time 将使用本地时区。您得到的差异将是本地时区和 UTC 之间的差异(以秒为单位)。
要解决这个问题,请在使用 timestamp() 之前指定时区。这可以通过使用 replace(tzinfo=pytz.UTC) 或更好地在 strftime 和 strptime 中使用格式 "%Y-%m-%dT%H:%M:%S.%f%z" 来完成.