Python Forum

Full Version: Confusion with datetime 'dst' function result
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have found the result of the datetime 'dst' funtion to be confusing. If I create a datetime object this way:

import datetime, pytz
myDate = datetime.datetime.now(tz=pytz.timezone("US/Eastern"))

and then type

print(myDate.timetuple().tm_isdt)

I get a '0', which correctly means that my date/time is not during daylight saving time. But then I create a new date with

newDate = myDate - datetime.timedelta(days=180)

which gives me a date/time on May 19, 2019. But if I type

print(newDate.timetuple().tm_isdt)

I still get a '0' even though my new date is during daylight saving time. Or, more practically, the statement

print(myDate.dst() == newDate.dst())

results in 'True' even though one date was during daylight saving time and the other wasn't. Is there a way to avoid this confusion (other than limiting any usage of the 'dst' function to the line immediately after a datetime object is created)?
I'm not sure that's what pytz is for. I think it is meant to be used for converting one time between two time zones, not for dealing with two different times in the same time zone.

Fun fact: pytz uses what is sometimes called the 'Olson database', after the founding contributor, Arthur David Olson. I know Arthur David. He lives near me, and we used to run into each other a lot.
I'm not able to answer the question but from what I read elsewhere, using the arrow module could be the solution to these issues.
>>> import arrow
>>> a = arrow.now('US/Eastern')
>>> a
<Arrow [2019-11-15T15:34:42.463220-05:00]>
>>> b = a.shift(days=-180)
>>> b
<Arrow [2019-05-19T15:34:42.463220-04:00]>
>>> a.dst()
datetime.timedelta(0)
>>> b.dst()
datetime.timedelta(0, 3600)
It's the same for my when test this.
Rather than try to figure what's going on,i would use Pendulum .
It provides drop-in replacements for datetime,pytz...ect (or inherit from them if needed).
Timezone is a really strong part that's done right.
>>> import pendulum
>>> 
>>> # Now not daylight savings time
>>> dt = pendulum.datetime(2019, 11, 15, tz='Europe/Berlin')
>>> dt.is_dst()
False

>>> # Go back to when it was daylight savings time(Norway)
>>> dt = pendulum.datetime(2019, 7, 15, tz='Europe/Berlin')
>>> dt.is_dst()
True 
Working with pytz requires knowledge how to use it right.
If you make a mistake, you get strange results.

I like the pendulum module more, because you have lesser to write.