Reputation: 1
The total second difference between 2 datetime objects set in different time zones but on the same date does not yield 0.0 in some circumstances.
import datetime
from pytz import timezone
from dateutil import parser
print(datetime.datetime.now(timezone('US/Eastern')))
print(datetime.datetime.now(timezone('America/Vancouver')))
print((datetime.datetime.now(timezone('US/Eastern')) - datetime.datetime.now(timezone('America/Vancouver'))).total_seconds())
print((datetime.datetime(2011, 8, 15, 8, 0, 0, 0, timezone('America/Vancouver')) - datetime.datetime(2011, 8, 15, 11, 0, 0, 0, timezone('US/Eastern'))).total_seconds())
print((datetime.datetime(2011, 8, 15, 8, 0, 0, 0, timezone('America/Vancouver')) - datetime.datetime(2011, 8, 15, 11, 16, 0, 0, timezone('US/Eastern'))).total_seconds())
print((parser.parse("2011-08-15 08:00:00 UTC-4") - parser.parse("2011-08-15 11:00:00 UTC-7")).total_seconds())
For the third, fourth, and last output of the print statements I would expect them to be all 0.0. I would expect the fifth to be 960.0. However, it seems that when finding the difference of the same date in different time zones using a specific datetime.datetime constructor, it leads to a timezone difference of 3h and 16 minutes between US/Eastern and America/Vancouver.
My output is below:
2024-07-22 12:02:44.950826-04:00
2024-07-22 09:02:44.951827-07:00
0.0
960.0
0.0
0.0
I printed out the datetime
objects from a suggestion and had interesting results!
print(datetime.datetime(2011, 8, 15, 8, 0, 0, 0, timezone('America/Vancouver')))
print(datetime.datetime(2011, 8, 15, 11, 0, 0, 0, timezone('US/Eastern')))
Resulted with:
2011-08-15 08:00:00-08:12
2011-08-15 11:00:00-04:56
The time difference is 8:12 and 4:56, the hours makes sense because of daylight saving time but I don't quite understand yet the minutes. Why it isn't on the hour? As in it isn't 8:00 and 5:00 respectively.
Am I doing something wrong? I'm sure there is a proper explanation. Thank you for your help!
Answer found:
It seems that I got confused, since you can input pytz.utc but not a timezone object as an argument. (As seen in this post: stackoverflow.com/a/7065242/8022722) (and in the docs: pythonhosted.org/pytz) It seems that in my case I had to localize the timezone as seen here: stackoverflow.com/a/5946616/8022722 and in the docs as well. I will close my question.
Upvotes: 0
Views: 42