I am wondering why the delta is 3601 seconds when it should be 1 second:
from datetime import datetime
from dateutil import tz
# Create eastern timezone
eastern = tz.gettz('America/New_York')
# 2017-03-12 01:59:59 in Eastern Time (EST)
spring_ahead_159am = datetime(2017, 3, 12, 1, 59, 59, tzinfo = eastern)
# 2017-03-12 03:00:00 in Eastern Time (EDT)
spring_ahead_3am = datetime(2017, 3, 12, 3, 0, 0, tzinfo = eastern)
(spring_ahead_3am - spring_ahead_159am).seconds
3601
Please explain me what I am doing wrong? Why it's not giving me 1 second diff?
P.S:
Please explain why this will do work easily: Let:
EST = timezone(timedelta(hours=-5))
EDT = timezone(timedelta(hours=-4))
spring_ahead_159am = datetime(2017, 3, 12, 1, 59, 59, tzinfo = EST)
spring_ahead_3am = datetime(2017, 3, 12, 3, 0, 0, tzinfo = EDT)
(spring_ahead_3am - spring_ahead_159am).seconds
1
This is a little quirk of datetime objects. Quoting from the documentation:
Subtraction of a datetime from a datetime is defined only if both operands are naive, or if both are aware. If one is aware and the other is naive, TypeError is raised.
If both are naive, or both are aware and have the same tzinfo attribute, the tzinfo attributes are ignored, and the result is a timedelta object t such that datetime2 + t == datetime1. No time zone adjustments are done in this case.
You can certain get what you want by subtracting their DST components:
>>> spring_ahead_3am - spring_ahead_3am.dst() - spring_ahead_159am + spring_ahead_159am.dst()
datetime.timedelta(seconds=1)
Update
Consider using this function, which does the Right Thing across timezones and DST changes:
def datesub( dt1, dt2 ):
return datetime.timedelta( seconds=dt2.timestamp()-dt1.timestamp() )