6

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!

SparkAndShine
  • 17,001
  • 22
  • 90
  • 134
Mars J
  • 902
  • 3
  • 15
  • 23
  • I think maybe this link can help? http://stackoverflow.com/questions/5259882/subtract-two-times-in-python "Use the `combine` to builds a datetime, that can be subtracted. " – George Apr 03 '12 at 18:35
  • 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 Jun 15 '19 at 09:04

2 Answers2

13

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.

nOw2
  • 656
  • 7
  • 13
  • Okay great. That makes sense. I am new to django and working with datetime objects... could you point me towards more information about doing those conversions? Thanks! – Mars J Apr 03 '12 at 19:07
  • Added a note for pytz which is what I used. – nOw2 Apr 03 '12 at 21:47
  • Were you able to use the information to do what you wanted? If so, could you click to accept the answer? Thanks! – nOw2 Apr 11 '12 at 12:29
1

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.

yasir
  • 13
  • 4