2
votes

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!

2
I think maybe this link can help? stackoverflow.com/questions/5259882/… "Use the combine to builds a datetime, that can be subtracted. "George
Pardon but meanwhile perhaps we might want to consider the definition of "naive": (of a person or action) showing a lack of experience, wisdom, or judgment. It is not the opposite of aware. So the correct and logical term would be "timezone unaware". Developers of datetime, pytz etc please correct this going forward.gseattle

2 Answers

7
votes

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.

1
votes

Use :

    now = now.replace(tzinfo=past_time.tzinfo)

before diff = now - past_time.

so that both now and past_time have same tzinfo.

only if now and past_time intended to be in same timezone.