I don't understand why a isn't the same as b:
import pandas as pd
from datetime import datetime
import pytz
here = pytz.timezone('Europe/Amsterdam')
a = pd.Timestamp('2018-4-9', tz=here).to_pydatetime()
# datetime.datetime(2018, 4, 9, 0, 0, tzinfo=<DstTzInfo'Europe/Amsterdam' CEST+2:00:00 DST>)
b = datetime(2018, 4, 9, 0, tzinfo=here)
# datetime.datetime(2018, 4, 9, 0, 0, tzinfo=<DstTzInfo 'Europe/Amsterdam' LMT+0:20:00 STD>)
print(b-a)
# returns 01:40:00
From this stackoverflow post I learned that tzinfo doesn't work well for some timezones and that could be the reason for the wrong result.
pytz doc:
Unfortunately using the tzinfo argument of the standard datetime constructors ‘’does not work’’ with pytz for many timezones.
The solution is to use localize or astimezone:
import pandas as pd
from datetime import datetime
import pytz
here = pytz.timezone('Europe/Amsterdam')
a = pd.Timestamp('2018-4-9', tz=here).to_pydatetime()
# datetime.datetime(2018, 4, 9, 0, 0, tzinfo=<DstTzInfo'Europe/Amsterdam' CEST+2:00:00 DST>)
b = here.localize(datetime(2018, 4, 9))
# datetime.datetime(2018, 4, 9, 0, 0, tzinfo=<DstTzInfo 'Europe/Amsterdam' CEST+2:00:00 DST>)
print(b-a)
# returns 00:00:00
If you look at a and b,
a
datetime.datetime(2018, 4, 9, 0, 0, tzinfo=<DstTzInfo 'Europe/Amsterdam' CEST+2:00:00 DST>)
verus
b
datetime.datetime(2018, 4, 9, 0, 0, tzinfo=<DstTzInfo 'Europe/Amsterdam' LMT+0:20:00 STD>)
CEST European Central Summer Time
vs
LMT Local Mean Time
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With