pytz difference of 2 datetimes in seconds? (Different time zones)

我们两清 提交于 2019-12-04 05:39:33

问题


I have 2 datetime objects with 2 different time zones:

datetime1 = 18:26:23, with tzinfo = UTC

datetime2 = 14:30:00, with tzinfo = US/Eastern

Both dates are on the same day.

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 gives me a value of: 3576.

Am I doing the difference in seconds wrong? Or am I not utilizing pytz for time zones correctly?

Many thanks.


回答1:


There are two likely scenarios here.

  1. Either you are creating the timezone on your datetime objects incorrectly
  2. The timezone is correct but your datetime objects are not actually representing the time you say they are.

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.

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



回答2:


doc for timedelta: https://docs.python.org/2/library/datetime.html

def make_timedelta(seconds):
        return timedelta(days=seconds // 86399, seconds=seconds % 86399)


来源:https://stackoverflow.com/questions/30380678/pytz-difference-of-2-datetimes-in-seconds-different-time-zones

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!