1

In python3.4, if I create a timezone aware datetime objet, how do I determine whether the given date is summer (dst) or winter time?

Example:

local_time = pytz.timezone('Europe/Berlin')
time_winter = datetime.datetime(2014, 11, 26, 10, tzinfo=local_time)
time_summer = datetime.datetime(2014, 7, 26, 10, tzinfo=local_time)

In both cases .dst() returns off:

>>> datetime.timedelta(0)

Also .tzname() and .tzinfo() are always the same.

In principle, the object is aware of the timezone and dst, but only sometimes:

cet_winter = pytz.timezone('CET')    #    CET is without dst

datetime.datetime(2014,7 , 26, 10, tzinfo=local_time).astimezone(cet_winter)
>>> datetime.datetime(2014, 7, 26, 11, 0, tzinfo=<DstTzInfo 'CET' CEST+2:00:00 DST>)


datetime.datetime(2014,11, 26, 10, tzinfo=local_time).astimezone(cet_winter)
>>> datetime.datetime(2014, 11, 26, 10, 0, tzinfo=<DstTzInfo 'CET' CET+1:00:00 STD>)

Here it shows a difference between summer and winter time... Doing the same to UTC, it won't work...

datetime.datetime(2014,11, 26, 10, tzinfo=local_time).astimezone(pytz.timezone('UTC'))
>>> datetime.datetime(2014, 11, 26, 9, 0, tzinfo=<UTC>)

datetime.datetime(2014,11, 26, 10, tzinfo=local_time).astimezone(pytz.timezone('UTC'))
>>> datetime.datetime(2014, 11, 26, 9, 0, tzinfo=<UTC>)

Do I miss something fundamentally or do I need to make the timezone object time dependent?

Jochen
  • 155
  • 1
  • 3
  • 15
  • See also: http://stackoverflow.com/questions/19774709/use-python-to-find-out-if-a-timezone-currently-in-daylight-savings-time – Simeon Visser Nov 21 '14 at 16:59

1 Answers1

1

You need to use localize on the timezone object:

>>> local_time.localize(datetime.datetime(2014, 11, 26, 10)).dst()
datetime.timedelta(0)
>>> local_time.localize(datetime.datetime(2014, 7, 26, 10)).dst()
datetime.timedelta(0, 3600)

Both .localize() and .normalize() are used to ensure conversion is done correctly and takes DST into account (see examples).

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
  • 1
    Just to add because I first misunderstood: If your time zone has dst, you MAY NOT set your timezone simply as tz argument, but you have to pass it via localize. The initialization as in my question is wrong, it would need to be: time_winter = local_time.localize(datetime.datetime(2014, 11, 26, 10)) – Jochen Nov 24 '14 at 09:14