3

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
Tony
  • 445
  • 6
  • 13

2 Answers2

3

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
João Abrantes
  • 4,772
  • 4
  • 35
  • 71
1

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

Scott Boston
  • 147,308
  • 15
  • 139
  • 187
  • It seems that here CEST is the same as LMT time, but pandas and python interpret the same time zone differently? – Tony Apr 12 '18 at 09:38