Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Figure out local timezone

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?

like image 689
Adam Matan Avatar asked Apr 27 '10 10:04

Adam Matan


People also ask

How do I get local time zone in Python?

To get the current time in particular, you can use the strftime() method and pass into it the string ”%H:%M:%S” representing hours, minutes, and seconds.

How do I find my local time zone?

To get the current browser's time zone, you can use the getTimezoneOffset() method from the JavaScript Date object. The getTimezoneOffset() returns the time difference, in minutes, between UTC time and local time.

What is Tzlocal in Python?

tzlocal looks for the timezone name in /etc/timezone, /var/db/zoneinfo, /etc/sysconfig/clock and /etc/conf. d/clock. If your /etc/localtime is a symlink it can also extract the name from that symlink. If you need the name of your local time zone, then please make sure your system is properly configured to allow that.

How do you convert UTC to local time in Python?

This datetime object will have no timezone associated with it. Therefore assign the UTC timezone to this datetime object using replace(tzinfo=pytz. UTC) function. Convert the timezone of the datetime object to local timezone by calling the astimezone() function on datetime object.


2 Answers

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

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

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

For python < 3.6, you'll need

import datetime LOCAL_TIMEZONE = datetime.datetime.now(datetime.timezone(datetime.timedelta(0))).astimezone().tzinfo 
like image 95
vbem Avatar answered Sep 20 '22 10:09

vbem


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

like image 32
Steven Avatar answered Sep 18 '22 10:09

Steven