Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

timezone aware vs. timezone naive in python

I am working with datetime objects in python. I have a function that takes a time and finds the different between that time and now.

def function(past_time):
    now = datetime.now()
    diff = now - past_time

When I initialized past_time before passing it to this function I initialized it as datetime naive. And now is also a datetime naive object. However when I try to call this function I get the error: can't subtract offset-naive and offset-aware datetimes. How come this is the case if they are both theoretically datetime naive objects?

Any help would be appreciated. Thanks!

like image 347
Mars J Avatar asked Dec 28 '22 03:12

Mars J


1 Answers

datetime doesn't do any cross time zone calculations, because it's a complex and involved subject.

I suggest converting dates to UTC universally and performing maths on those.

I recently completed a project using timezones in a large python/Django project and after investigation went with converting everything internally to UTC and converting only on display to the user.

You should look into pytz to do the conversions to/from UTC, and store Olson codes for the timezones you want in your app - perhaps associated with each user, or appropriate to your program.

like image 88
nOw2 Avatar answered Jan 13 '23 21:01

nOw2