Python Datetime | Timezone-Aware and Naive
Start your free 7-days trial now!
Timezone-Aware datetime object: does have a timezone associated with it.
Timezone-Naïve datetime object: does not have any timezone associated with it.
Rules of thumb
Always work with "timezone-aware" datetime objects.
Always store datetime in UTC and leave rendering of timezones to the front-end.
You may often hear the term “offset” when dealing with timezones. Offset of a timezone refers to the difference in hours from Coordinated Universal Time (UTC).
Examples
Checking whether a datetime object is timezone-naive
Python’s tzinfo
abstract class can be used to check whether there is timezone information associated with a datetime object. It will return None
if the object is timezone-naïve.
import datetime
naive = datetime.datetime.now()print(naive.tzinfo)
None
As this example shows, datetime objects instantiated using datetime
class are timezone-naïve.
Making a naive datetime object aware
The localize()
method within the pytz
module is used to make a naïve datetime object timezone aware.
from datetime import datetimefrom pytz import timezone # Set the time to noon on 2020-03-22naive = datetime(2020, 3, 22, 12, 00)print("Naive timezone = ", naive.tzinfo) # Let's treat this time as being in the UTC timezoneaware = timezone('UTC').localize(naive)print("Aware timezone = ", aware.tzinfo)
Naive timezone = NoneAware timezone = UTC
Localize a datetime object using timezone other than UTC
First, you have to instantiate a timezone
object, and then use that timezone
object to localize a datetime
object.
import datetimeimport pytz
naive = datetime.datetime.now()print("Naive = ", naive) timezone = pytz.timezone("Asia/Tokyo")aware = timezone.localize(naive)print("Aware = ", aware)
Naive = 2020-03-22 09:46:11.056746Aware = 2020-03-22 09:46:11.056746+09:00
We have now attached timezone information (UTC +09:00) to the timezone-naïve datetime object to make it an timezone-aware object.