ISO time (ISO 8601) in Python ISO time (ISO 8601) in Python python python

ISO time (ISO 8601) in Python

Local to ISO 8601:

import>>> 2020-03-20T14:28:23.382748

UTC to ISO 8601:

import datetimedatetime.datetime.utcnow().isoformat()>>> 2020-03-20T01:30:08.180856

Local to ISO 8601 without microsecond:

import>>> 2020-03-20T14:30:43

UTC to ISO 8601 with TimeZone information (Python 3):

import datetimedatetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()>>> 2020-03-20T01:31:12.467113+00:00

UTC to ISO 8601 with Local TimeZone information without microsecond (Python 3):

import>>> 2020-03-20T14:31:43+13:00

Local to ISO 8601 with TimeZone information (Python 3):

import>>> 2020-03-20T14:32:16.458361+13:00

Notice there is a bug when using astimezone() on utc time. This gives an incorrect result:

datetime.datetime.utcnow().astimezone().isoformat() #Incorrect result

For Python 2, see and use pytz.

Here is what I use to convert to the XSD datetime format:

from datetime import You get your ISO string

I came across this question when looking for the XSD date time format (xs:dateTime). I needed to remove the microseconds from isoformat.

ISO 8601 Time Representation

The international standard ISO 8601 describes a string representation for dates and times. Two simple examples of this format are

2010-12-16 17:22:1520101216T172215

(which both stand for the 16th of December 2010), but the format also allows for sub-second resolution times and to specify time zones. This format is of course not Python-specific, but it is good for storing dates and times in a portable format. Details about this format can be found in the Markus Kuhn entry.

I recommend use of this format to store times in files.

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>>> strftime("%Y-%m-%d %H:%M:%S")'2010-03-03 21:16:45'

You can use the strptime constructor of the datetime class:

>>> from datetime import datetime>>> datetime.strptime("2010-06-04 21:08:12", "%Y-%m-%d %H:%M:%S")datetime.datetime(2010, 6, 4, 21, 8, 12)

The most robust is the Egenix mxDateTime module:

>>> from mx.DateTime.ISO import ParseDateTimeUTC>>> from datetime import datetime>>> x = ParseDateTimeUTC("2010-06-04 21:08:12")>>> datetime.fromtimestamp(x)datetime.datetime(2010, 3, 6, 21, 8, 12)