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



Question:

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


Solution:1

>>> 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'  >>>   


Solution:2

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.


Solution:3

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))  


Solution:4

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


Solution:5

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

http://labix.org/python-dateutil#head-50221b5226c3ccb97daa06ea7d9abf0533ec0310


Solution:6

Maybe try:

import time

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


Solution:7

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:

time.strftime("%z")  

[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
Previous
Next Post »