10

I need to subtract a timezone aware datetime.now() with datetime.min, but i keep getting this error TypeError: can't subtract offset-naive and offset-aware datetimes. Please help!

from datetime import datetime
from pytz import timezone
now = datetime.now(timezone('Europe/Dublin'))
result = now - datetime.min
3
  • I guess you have checked that answer right ? (stackoverflow.com/questions/796008/…)
    – Nqsir
    May 24, 2019 at 7:10
  • Yes, I have checked this post the first answer is to remove timezone awareness and the second solution was for making datetime.now() aware, but my requirement is to make datetime.min aware May 24, 2019 at 7:18
  • MAking datetime.min aware is going to be... interesting. Do it the other way round
    – Will
    May 24, 2019 at 7:21

1 Answer 1

11

You can convert it to UTC:

In [1]: from datetime import datetime

In [2]: import pytz

In [3]: dt_min = datetime.min

In [4]: print(dt_min)
0001-01-01 00:00:00

In [5]: dt_min = dt_min.replace(tzinfo=pytz.UTC)

In [6]: print(dt_min)
0001-01-01 00:00:00+00:00

So your code would be:

from datetime import datetime
import pytz
now = datetime.now(pytz.timezone('Europe/Dublin'))
dt_min = datetime.min
result = now - dt_min.replace(tzinfo=pytz.UTC)
print(result)

output:
737202 days, 7:27:48.839353
2
  • 2
    Better answer than mine
    – Will
    May 24, 2019 at 7:30
  • pytz is now included in datetime Mar 31, 2022 at 18:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.