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?
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.
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.
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.
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.
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
Try dateutil, which has a tzlocal type that does what you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With