Working with Dates and Times in Python
Max Shron
Data Scientist and Author
spring_ahead_159am = datetime(2017, 3, 12, 1, 59, 59)
spring_ahead_159am.isoformat()
'2017-03-12T01:59:59'
spring_ahead_3am = datetime(2017, 3, 12, 3, 0, 0)
spring_ahead_3am.isoformat()
'2017-03-12T03:00:00'
(spring_ahead_3am - spring_ahead_159am).total_seconds()
3601.0
from datetime import timezone, timedelta
EST = timezone(timedelta(hours=-5))
EDT = timezone(timedelta(hours=-4))
spring_ahead_159am = spring_ahead_159am.replace(tzinfo = EST)
spring_ahead_159am.isoformat()
'2017-03-12T01:59:59-05:00'
spring_ahead_3am = spring_ahead_3am.replace(tzinfo = EDT)
spring_ahead_3am.isoformat()
'2017-03-12T03:00:00-04:00'
(spring_ahead_3am - spring_ahead_159am).seconds
1
Using dateutil
# Import tz 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)
Working with Dates and Times in Python