In this tutorial we are going to explore how to make naive datetime objects time zone aware in python.
In a previous article, I covered how you can convert a datetime to UTC in python, which is a very common task in software development.
A prerequisite for converting a datetime to UTC or any other time zone is that your datetime object is time zone aware.
So, let’s go over a few ways we can make datetime objects time zone aware.
Using The Datetime Replace Method
tz = pytz.timezone('US/Eastern')
aware_datetime = d.replace(tzinfo=tz)
Using this method is acceptable if the time zone you are using does not have multiple offsets. A time zone may have multiple offsets, due to things like daylight savings. UTC for example only has one offset. So if your datetime is in UTC, this example will work fine. However, in general, I probably would avoid this method just to be safe. There are much better options.
Using The pytz Timezone Localize Method
tz = pytz.timezone('America/Chicago')
aware_datetime = tz.localize(my_naive_datetime)
In this example, we use the localize method of a pytz timezone object. This method will work for any time zone and is very easy to use. Also, you do not need to worry about the offset issue that I mentioned in the previous example. This is solid choice.
Now let’s take a look at an example that uses the arrow package. If you have not heard of arrow, it is a really cool python package for date manipulation that highly emphasizes ease-of-use.
Using the Arrow Package
arrow_object = arrow.get(my_naive_datetime, 'US/Pacific')
### datetime.datetime(2013, 5, 7, 4, 38, 15, 447644, tzinfo=tzutc())
Isn’t this awesome! I love how easy the arrow packages is to use!
If you are interested in arrow, check out my previous article where I show how you can convert a datetime object to UTC using arrow.
That’s all folks!
If you liked this and want to read more python content, check out these other python articles I wrote.
Have a good day!