Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert datetime.min into offset aware datetime

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
like image 264
Pavan Skipo Avatar asked May 24 '19 07:05

Pavan Skipo


1 Answers

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
like image 168
Amir Shabani Avatar answered Sep 21 '22 12:09

Amir Shabani