Tutorial :how to get tz_info object corresponding to current timezone?


Is there a cross-platform function in python (or pytz) that returns a tzinfo object corresponding to the timezone currently set on the computer?

environment variables cannot be counted on as they are not cross-platform


>>> import datetime  >>> today = datetime.datetime.now()  >>> insummer = datetime.datetime(2009,8,15,10,0,0)  >>> from pytz import reference  >>> localtime = reference.LocalTimezone()  >>> localtime.tzname(today)  'PST'  >>> localtime.tzname(insummer)  'PDT'  >>>   


tzlocal module that returns pytz timezones works on *nix and win32:

from datetime import datetime  from tzlocal import get_localzone # $ pip install tzlocal    # get local timezone      local_tz = get_localzone()       print local_tz.localize(datetime(2012, 1, 15))  # -> 2012-01-15 00:00:00+04:00 # current utc offset  print local_tz.localize(datetime(2000, 1, 15))  # -> 2000-01-15 00:00:00+03:00 # past utc offset (note: +03 instead of +04)  print local_tz.localize(datetime(2000, 6, 15))  # -> 2000-06-15 00:00:00+04:00 # changes to utc offset due to DST  

Note: it takes into account both DST and non-DST utc offset changes.


This following code snippet returns time in a different timezone irrespective of the timezone configured on the server.

# pip install pytz tzlocal    from tzlocal import get_localzone  from datetime import datetime  from pytz import timezone    local_tz = get_localzone()  local_datetime = datetime.now(local_tz)    zurich_tz = timezone('Europe/Zurich')  zurich_datetime = zurich_tz.normalize(local_datetime.astimezone(zurich_tz))  


time.timezone returns current timezone offset. there is also a datetime.tzinfo, if you need more complicated structure.


I have not used it myself, but dateutil.tz.tzlocal() should do the trick.



Maybe try:

import time

print time.tzname #or time.tzname[time.daylight]


I was asking the same to myself, and I found the answer in [1]:

Take a look at section 8.1.7: the format "%z" (lowercase, the Z uppercase returns also the time zone, but not in the 4-digit format, but in the form of timezone abbreviations, like in [3]) of strftime returns the form "+/- 4DIGIT" that is standard in email headers (see section 3.3 of RFC 2822, see [2], which obsoletes the other ways of specifying the timezone for email headers).

So, if you want your timezone in this format, use:


[1] http://docs.python.org/2/library/datetime.html

[2] http://tools.ietf.org/html/rfc2822#section-3.3

[3] Timezone abbreviations: http://en.wikipedia.org/wiki/List_of_time_zone_abbreviations , only for reference.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »