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?
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.
In Python 3.x, local timezone may can be figure out like this:
It's a tricky use of
datetime
's code .Here's a slightly more concise version of @vbem's solution:
The only substantive difference is that I replaced
datetime.datetime.now(datetime.timezone.utc)
withdatetime.datetime.utcnow()
. For brevity, I also aliaseddatetime.datetime
asdt
.For my purposes, I want the UTC offset in seconds. Here's what that looks like:
First get pytz and tzlocal modules
then
then you can do things like
tzlocal from dateutil.
Code example follows. Last string suitable for use in filenames.
Try dateutil, which has a tzlocal type that does what you need.