Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using python to determine if a timestamp is under daylight savings time

This does not work:

t = os.path.getmtime(filename)
dTime = datetime.datetime.fromtimestamp(t)
justTime = dTime.timetuple()
if justTime.tm_isdst == 0 :
    tDelta = datetime.timedelta(hours=0)
else:
    tDelta = datetime.timedelta(hours=1)

What happens instead is that the conditional always equals 1, despite some of the timestamps being within daytime savings time.

I am trying to make a python call match the behavior of a c-based call.

like image 927
Jiminion Avatar asked Apr 08 '16 18:04

Jiminion


People also ask

How do you know if its daylight savings time in python?

dst() method which returns the daylight saving time difference at any point. If the timestamp occurs during daylight saving time, it returns a datetime. timedelta value of one hour. If the timestamp does not occur during daylight saving time, it returns a datetime.

How does Python handle daylight time?

daylight() Function. Time. daylight() function which returns a non zero integer value when Daylight Saving Time (DST) is defined, else it returns 0.

How do you determine Daylight Savings Time?

In the U.S., daylight saving time starts on the second Sunday in March and ends on the first Sunday in November, with the time changes taking place at 2:00 a.m. local time.

What is the function to offset the date for daylight saving Python?

utcoffset(dt) - This method is used to get the DST offset in the zones where DST is in effect. If the DST is not in effect, it will return only timedelta(0). The DTC information is already part of the UTC offset.


1 Answers

To find out whether a given timestamp corresponds to daylight saving time (DST) in the local time zone:

import os
import time

timestamp = os.path.getmtime(filename)
isdst = time.localtime(timestamp).tm_isdst > 0

It may fail. To workaround the issues, you could get a portable access to the tz database using pytz module:

from datetime import datetime
import tzlocal  # $ pip install tzlocal

local_timezone = tzlocal.get_localzone() # get pytz tzinfo
isdst = bool(datetime.fromtimestamp(timestamp, local_timezone).dst())

Related: Use Python to find out if a timezone currently in daylight savings time.

like image 53
jfs Avatar answered Nov 15 '22 00:11

jfs