DEV Community

Anas Kanhouch
Anas Kanhouch

Posted on

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 = # 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 = # 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 ='UTC'))
t1 ='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

Top comments (0)