Martin Taleski
Martin Taleski

Reputation: 6448

Get the offset for a specific time and timezone in python

I need a function that will return the offset for a specific timezone at a specific moment. I have the timezone in a string variable in the format America/Los_Angeles and I have the date in format 2014-12-01

The offset needs to be DST sensitive, meaning that for Los Angeles, it should return -07 during summer and -08 during winter.

Upvotes: 2

Views: 747

Answers (1)

Mark Ransom
Mark Ransom

Reputation: 308091

You can convert the string into a timezone object with pytz:

tz = pytz.timezone('America/Los_Angeles')

Convert the date to a datetime object with strptime:

dt = datetime.datetime.strptime('2014-12-01', '%Y-%m-%d')

Now the hour offset can be derived:

offset = int(tz.utcoffset(dt).total_seconds() / 3600.0)

Upvotes: 4

Related Questions