Dealing with datetime objects and time zones in Python 3
Working with datetime objects and time zones is one of those things I always struggle with when writing code in Python. I always have to look things up and double check the outputs (such as making sure daylight savings time was taken into account) to make sure I'm doing things correctly.
This blog post is really more of a reference for myself when making adjustments to datetime objects that involve time zones so I won't go into detail here about how this works.
First thing is to make sure you have the pytz and python-dateutil packages installed as they will make things a lot easier:
pip install pytz python-dateutil
Making datetime objects "aware"
It's a good idea to always convert local times to UTC first before making any adjustments.
import datetime import pytz now_utc = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
Convert current local time to another timezone
import datetime import pytz now_utc = datetime.datetime.utcnow().replace(tzinfo=pytz.utc) nyc_timezone = pytz.timezone('America/New_York') nyc_local_time = nyc_timezone.normalize(now_utc.astimezone(nyc_timezone)) la_timezone = pytz.timezone('America/Los_Angeles') la_local_time = la_timezone.normalize(now_utc.astimezone(la_timezone))
Converting a string and naive datetime object to a timezone-aware datetime object
import pytz from dateutil import parser nyc_time_string = '2019-06-29 22:32:59' nyc_time_naive = parser.parse(nyc_time_string) nyc_timezone = pytz.timezone('America/New_York') nyc_local_time = nyc_timezone.localize(nyc_time_naive) # Convert to UTC. utc_time = pytz.utc.normalize(nyc_local_time.astimezone(pytz.utc)) # Convert to Los Angeles time. la_timezone = pytz.timezone('America/Los_Angeles') la_local_time = la_timezone.normalize(utc_time.astimezone(la_timezone)) # Convert to Bangkok time. bangkok_timezone = pytz.timezone('Asia/Bangkok') bangkok_local_time = bangkok_timezone.normalize(utc_time.astimezone(bangkok_timezone))
The pytz module will also automatically figure out the correct adjustments for daylight savings time if necessary.
Tags: python, tech, software development