pytz 2日期时间的差异,以秒为单位? (不同时区) [英] pytz difference of 2 datetimes in seconds? (Different time zones)
问题描述
我有2个具有两个不同时区的datetime对象:
I have 2 datetime objects with 2 different time zones:
datetime1 = 18:26:23,tzinfo = UTC
datetime1 = 18:26:23, with tzinfo = UTC
datetime2 = 14:30:00,其中tzinfo =美国/东部
datetime2 = 14:30:00, with tzinfo = US/Eastern
两个日期都在同一天。
两个日期时间之间应该精确地相差1小时,3分钟和37秒,即:3817秒的总时差。
There should be exactly 1 hour, 3 minutes and 37 seconds difference between the 2 datetimes, which is: 3817 seconds total difference.
但是,当我使用以下代码进行比较时:
However, when I use the following code to compare:
time_diff = (datetime2 - datetime1).total_seconds()
time_diff给我一个值:3576。
time_diff gives me a value of: 3576.
我在几秒钟之内做错了吗?还是我不正确地将pytz用于时区?
Am I doing the difference in seconds wrong? Or am I not utilizing pytz for time zones correctly?
非常感谢。
推荐答案
这里有两种可能的情况。
There are two likely scenarios here.
- 您在日期时间对象上创建的时区不正确
- 时区正确,但是您的datetime对象实际上并不代表您所说的时间。
例如,无论时区如何,我都看不到 18:26:23
和 14:30:00
之间的时差可能会给你几秒钟的时间,这使场景2的可能性更高。
For example, regardless of timezone, I don't see how the diff between 18:26:23
and 14:30:00
could possibly give you an even number of seconds, which makes scenario #2 more likely.
您可以打印 datetime $的值吗? c $ c>对象,然后再运行以下行:
Can you print the value of the datetime
objects right before you run the line:
time_diff = (datetime2 - datetime1).total_seconds()
以下是一些示例代码,可为您提供预期的秒数:
Here is some sample code for reference that gives you the expected seconds:
from pytz import timezone
from datetime import datetime
eastern = timezone('US/Eastern')
utc = timezone('UTC')
datetime1 = utc.localize(datetime(2002, 10, 27, 18, 26, 23))
datetime2 = eastern.localize(datetime(2002, 10, 27, 14, 30, 00))
time_diff = (datetime2 - datetime1).total_seconds()
print(time_diff) # prints 3817
这篇关于pytz 2日期时间的差异,以秒为单位? (不同时区)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!