David Findlay David Findlay - 1 year ago 176
Python Question

Datetime object with timezone

How do I get an aware datetime object using the modified timestamp from a file? I've done it this way:

modified = datetime.datetime.fromtimestamp(os.path.getmtime(myfile))
isotime = modified.strftime('%Y-%m-%d %H:%M:%S %z')

but this just gets me a naive time, so %z is a blank string like: 2016-09-03 10:35:24

I've been using this documentation, but I can't understand how to make a tzinfo object for the system timezone: https://docs.python.org/2/library/datetime.html

Answer Source

It is pain in the ass to get the current time zone using python standart library.

Just install dateutil package:

$ sudo pip install python-dateutil

and you can do the following:


>>> from dateutil.tz import tzlocal
>>> datetime.datetime.fromtimestamp(os.path.getmtime("file"), tz=tzlocal())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download