13

I am trying to automate getting the local timezone offset but am having trouble. I've tried:

print time.timezone/3600

This gets the (currently wrong) offset as it doesn't automatically adjust for Daylight Savings Time and non-DST.

I've also tried:

now_utc = pytz.utc.localize(datetime.datetime.now())
now_mst = now_utc.astimezone(pytz.timezone('US/Mountain'))

This gets the correct offset value, but I'd like to set 'US/Mountain' part automatically so I don't have to manually input anything to get the offset.

Is there a way to get the correct offset that automatically adjusts with DST & non-DST?

I will be running this script on multiple servers in different geographies and I want to get the tz offset automatically if I can.

  • See also: [Get the Olson TZ name for the local timezone?](http://stackoverflow.com/questions/7669938/get-the-olson-tz-name-for-the-local-timezone). – Pedro Romano Oct 28 '12 at 22:32
  • 1
    related: [Getting computer's utc offset in Python](http://stackoverflow.com/q/3168096/4279) – jfs Sep 29 '14 at 12:30

1 Answers1

18

You can use the dateutil module for this. To get the local timezone right now:

>>> import dateutil.tz
>>> import datetime
>>> localtz = dateutil.tz.tzlocal()
>>> localtz.tzname(datetime.datetime.now(localtz))
'EDT'

I am currently in Eastern Daylight Time. You can see it change back to EST in the future, after daylight savings switches back:

>>> localtz.tzname(datetime.datetime.now(localtz) +
                   datetime.timedelta(weeks=20))
'EST'

If you want the offset from UTC, you can use the utcoffset function. It returns a timedelta:

>>> localtz.utcoffset(datetime.datetime.now(localtz))
datetime.timedelta(-1, 72000)

In this case, since I'm UTC-4, it returns -1 days + 20 hours. You can convert it to hours if that's what you need:

>>> localoffset = localtz.utcoffset(datetime.datetime.now(localtz))
>>> localoffset.total_seconds() / 3600
-4.0
jfs
  • 399,953
  • 195
  • 994
  • 1,670
jterrace
  • 64,866
  • 22
  • 157
  • 202
  • I need the local timezone offset, not the timezone –  Aug 18 '12 at 02:17
  • 1
    sorry, updated with how to get the offset – jterrace Aug 18 '12 at 02:42
  • `datetime.now()` may be ambiguous i.e., the code may return a wrong UTC offset during DST transitions, use `.now(local_tz)` to get the time unambiguously. – jfs Sep 29 '14 at 12:40
  • `dateutil` may fail for past/future dates if UTC offset was/will be different for the current timezone for reasons unrelated to DST e.g. try Europe/Moscow time zone in 2010-2015 period. Use `pytz` timezones that can return the correct UTC offset. – jfs Sep 29 '14 at 12:41
  • it is not enough to pass the timezone to `.now()` method. Try the code. You might need to change the method calls, see [the code example with `get_localzone()` in my answer](http://stackoverflow.com/a/3168394/4279) that works in the most general case. – jfs Sep 29 '14 at 15:39