Recipe3.8.Checking Whether Daylight Saving Time Is Currently in Effect


Recipe 3.8. Checking Whether Daylight Saving Time Is Currently in Effect

Credit: Doug Fort

Problem

You want to know whether daylight saving time is in effect in your local time zone today.

Solution

It's a natural temptation to check time.daylight for this purpose, but that doesn't work. Instead you need:

import time def is_dst( ):     return bool(time.localtime( ).tm_isdst)

Discussion

In my location (as in most others nowadays), time.daylight is always 1 because time.daylight means that this time zone has daylight saving time (DST) at some time during the year, whether or not DST is in effect today.

The very last item in the pseudo-tuple you get by calling time.localtime, on the other hand, is 1 only when DST is currently in effect, otherwise it's 0which, in my experience, is exactly the information one usually needs to check. This recipe wraps this check into a function, calling built-in type bool to ensure the result is an elegant true or False rather than a rougher 1 or 0optional refinements, but nice ones, I think. You could alternatively access the relevant item as time.localtime( )[-1], but using attribute-access syntax with the tm_isdst attribute name is more readable.

See Also

Library Reference and Python in a Nutshell about module time.





Python Cookbook
Python Cookbook
ISBN: 0596007973
EAN: 2147483647
Year: 2004
Pages: 420
Simiral book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net