name goes here
name goes here

Reputation: 290

Test if datetime.datetime is in daylight savings with .dst() function not returning value with pytz timezone

I am trying to test if an arbitrary localized datetime object is in daylight savings time or not.

This is a similar question to many already asked. eg. (Daylight savings time in Python)

In these boards, a way to test if a datetime is in DST is to use the built-in function .dst(). This is wrapped into bool like:

if bool(mydatetimeobject.dst()):
    print ("date is DST!")

However, whenever I make an aribtrary datetime and pass a tztimezone the .dst() function does not report anything. Its as if the timezone was not set!

Check this code snippet to see the issue:

>>> from datetime import datetime
>>> import pytz
>>> localtime = pytz.timezone('US/Central')

>>> mydate = datetime(2004,3,1)  # day in standard time
>>> localtime.localize(mydate)
datetime.datetime(2004, 3, 1, 0, 0, tzinfo=<DstTzInfo 'US/Central' CST-1 day, 18:00:00 STD>)
>>> mydate.dst()

>>> mydate = datetime(2004,5,1)  #day in daylight time
>>> localtime.localize(mydate)
datetime.datetime(2004, 5, 1, 0, 0, tzinfo=<DstTzInfo 'US/Central' CDT-1 day, 19:00:00 DST>)
>>> mydate.dst()
>>> bool(mydate.dst())
False

Upvotes: 7

Views: 9546

Answers (1)

Hannu
Hannu

Reputation: 12205

It works but you need to assign localtime.localize() result to a variable and compare that. Now you just display the output and check .dst() of the original, naive datetime.

a = localtime.localize(mydate)
bool(a.dst())

returns True (assuming mydate is in DST).

Upvotes: 4

Related Questions