Python iso 8601 timestamp portable#
If you need a portable solution use the pytz module that provides access to the tz database: > import os 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. > from datetime import datetime, timezone To convert a file ctime to an ISO 8601 time string while preserving the UTC offset in Python 3: > import os The ISO 8601 time format does not store a time zone name, only the corresponding UTC offset is preserved. The most robust is the Egenix mxDateTime module: > from mx.DateTime.ISO import ParseDateTimeUTC You can use the strptime constructor of the datetime class: > from datetime import datetime One way to get the current time in this representation is to use strftime from the time module in the Python standard library: > from time import strftime I recommend use of this format to store times in files. Details about this format can be found in the Markus Kuhn entry. This format is of course not Python-specific, but it is good for storing dates and times in a portable format. (which both stand for the 16th of December 2010), but the format also allows for sub-second resolution times and to specify time zones. Two simple examples of this format are 17:22:15 The international standard ISO 8601 describes a string representation for dates and times. This gives an incorrect result: ().astimezone().isoformat() #Incorrect result Notice there is a bug when using astimezone() on utc time. Local to ISO 8601 with TimeZone information (Python 3): import datetimeĭ().astimezone().isoformat() UTC to ISO 8601 with Local TimeZone information without microsecond (Python 3): import datetimeĭ().astimezone().replace(microsecond=0).isoformat() UTC to ISO 8601 with TimeZone information (Python 3): import datetimeĭ().replace(tzinfo=).isoformat() Local to ISO 8601 without microsecond: import datetimeĭ().replace(microsecond=0).isoformat()