The ISO 8601 time format does not store a time zone name, only the corresponding UTC offset is preserved.
To convert a file ctime to an ISO 8601 time string while preserving the UTC offset in Python 3:
>>> import os
>>> from datetime import datetime, timezone
>>> ts = os.path.getctime(some_file)
>>> dt = datetime.fromtimestamp(ts, timezone.utc)
>>> dt.astimezone().isoformat()
'2015-11-27T00:29:06.839600-05:00'
The code assumes that your local timezone is Eastern Time Zone (ET) and that your system provides a correct UTC offset for the given POSIX timestamp (ts
), i.e., Python has access to a historical timezone database on your system or the time zone had the same rules at a given date.
If you need a portable solution; use the pytz
module that provides access to the tz database:
>>> import os
>>> from datetime import datetime
>>> import pytz # pip install pytz
>>> ts = os.path.getctime(some_file)
>>> dt = datetime.fromtimestamp(ts, pytz.timezone('America/New_York'))
>>> dt.isoformat()
'2015-11-27T00:29:06.839600-05:00'
The result is the same in this case.
If you need the time zone name/abbreviation/zone id, store it separately.
>>> dt.astimezone().strftime('%Y-%m-%d %H:%M:%S%z (%Z)')
'2015-11-27 00:29:06-0500 (EST)'
Note: no, :
in the UTC offset and EST
timezone abbreviation is not part of the ISO 8601 time format. It is not unique.
Different libraries/different versions of the same library may use different time zone rules for the same date/timezone. If it is a future date then the rules might be unknown yet. In other words, the same UTC time may correspond to a different local time depending on what rules you use -- saving a time in ISO 8601 format preserves UTC time and the local time that corresponds to the current time zone rules in use on your platform. You might need to recalculate the local time on a different platform if it has different rules.