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?
Based on Thoku's answer above, here's an answer that resolves the time zone to the nearest half hour (which is relevant for some timezones eg South Australia's) :
First, note that the question presents an incorrect initialization of an aware datetime object:
creates an invalid instance. One can see the problem by computing the UTC offset of the resulting object:
(Note the result which is an odd fraction of an hour.)
To initialize an aware datetime properly using pytz one should use the
localize()
method as follows:Now, if you require a local pytz timezone as the new tzinfo, you should use the tzlocal package as others have explained, but if all you need is an instance with a correct local time zone offset and abbreviation then tarting with Python 3.3, you can call the
astimezone()
method with no arguments to convert an awaredatetime
instance to your local timezone:Avoiding non-standard module (seems to be a missing method of datetime module):
It is hard to find out Olson TZ name for a local timezone in a portable manner. Fortunately, you don't need it to perform the comparison.
tzlocal
module returns a pytz timezone corresponding to the local timezone:Unlike other solutions presented so far the above code avoids the following issues:
dateutil
) fail to take that into accountNote: to get timezone-aware datetime object from a naive datetime object, you should use*:
instead of:
*
is_dst=None
forces an exception if given local time is ambiguous or non-existent.If you are certain that all local timestamps use the same (current) utc offset for the local timezone then you could perform the comparison using only stdlib:
timestamp1
andtimestamp2
can be compared directly.Note:
timestamp1
formula works only if the UTC offset at epoch (datetime.fromtimestamp(0)
) is the same as nowfromtimestamp()
creates a naive datetime object in the current local timezoneutcfromtimestamp()
creates a naive datetime object in UTC.Based on J. F. Sebastian's answer, you can do this with the standard library:
Tested in 3.4, should work on 3.4+
For simple things, the following
tzinfo
implementation can be used, which queries the OS for time zone offsets: