Be Careful when Using Python Datetime Module

anasmk

Anas Kanhouch

Posted on September 23, 2020

Be Careful when Using Python Datetime Module

I was struggling with a bug for a while with Python datetime until I found the cause of the bug was using naive datetime object. I will not write what was the bug since it will make the post longer.

Datetime allow for naive datetime objects which means datetime object without a time zone. For example:

import datetime as dt

t = dt.datetime.now() # this is naive datetime object
print(t) # => 2020-09-23 22:28:36.836077 

the problem comes when you start to convert a datetime to string or to json using different community packages. The packages will make assumption that naive datetime object is based on UTC time or Local time. The time after converting will become different without knowing what the issue and without warning you are using naive datetime object. To avoid these kind of problems always use datetime module with time zone info, like this:

import datetime as dt
import pytz

t = dt.datetime.now(tz=pytz.utc) # this is aware datetime object
print(t) # => 2020-09-23 22:28:36.836077+00:00

You can specify any time zone you want like this


t = dt.datetime.now(tz=pytz.timezone('UTC'))
t1 = dt.datetime.now(tz=pytz.timezone('Asia/Riyadh'))

print(t) # => 2020-09-23 22:55:07.635498+00:00
print(t1) # => 2020-09-24 01:55:07.670677+03:00

To know the available list of time zones check this link on Wikipedia

💖 💪 🙅 🚩
anasmk
Anas Kanhouch

Posted on September 23, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related