Python: Figure out local timezone

2019-01-16 12:12发布

I want to compare UTC timestamps from a log file with local timestamps. When creating the local datetime object, I use something like:

>>> local_time=datetime.datetime(2010, 4, 27, 12, 0, 0, 0, 
                                 tzinfo=pytz.timezone('Israel'))

I want to find an automatic tool that would replace thetzinfo=pytz.timezone('Israel') with the current local time zone.

Any ideas?

14条回答
Viruses.
2楼-- · 2019-01-16 12:44

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.

查看更多
仙女界的扛把子
3楼-- · 2019-01-16 12:45

In Python 3.x, local timezone may can be figure out like this:

import datetime
LOCAL_TIMEZONE = datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo

It's a tricky use of datetime's code .

查看更多
Lonely孤独者°
4楼-- · 2019-01-16 12:46

Here's a slightly more concise version of @vbem's solution:

from datetime import datetime as dt

dt.utcnow().astimezone().tzinfo

The only substantive difference is that I replaced datetime.datetime.now(datetime.timezone.utc) with datetime.datetime.utcnow(). For brevity, I also aliased datetime.datetime as dt.

For my purposes, I want the UTC offset in seconds. Here's what that looks like:

dt.utcnow().astimezone().utcoffset().total_seconds()
查看更多
Root(大扎)
5楼-- · 2019-01-16 12:47

First get pytz and tzlocal modules

pip install pytz tzlocal

then

from tzlocal import get_localzone
local = get_localzone()

then you can do things like

from datetime import datetime
print(datetime.now(local))
查看更多
ら.Afraid
6楼-- · 2019-01-16 12:50

tzlocal from dateutil.

Code example follows. Last string suitable for use in filenames.

>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
>>> str(datetime.now(tzlocal()))
'2015-04-01 11:19:47.980883-07:00'
>>> str(datetime.now(tzlocal())).replace(' ','-').replace(':','').replace('.','-')
'2015-04-01-111947-981879-0700'
>>> 
查看更多
做个烂人
7楼-- · 2019-01-16 12:53

Try dateutil, which has a tzlocal type that does what you need.

查看更多
登录 后发表回答