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
BadRequest
  • 382
  • 1
  • 14
Pavan Skipo
  • 1,757
  • 12
  • 29
  • I guess you have checked that answer right ? (https://stackoverflow.com/questions/796008/cant-subtract-offset-naive-and-offset-aware-datetimes) – Nqsir May 24 '19 at 07: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 – Pavan Skipo May 24 '19 at 07:18
  • MAking datetime.min aware is going to be... interesting. Do it the other way round – Will May 24 '19 at 07:21

1 Answers1

12

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
Amir Shabani
  • 3,857
  • 6
  • 30
  • 67