ISO 8601

From Simson Garfinkel
Jump to navigationJump to search

Converting between ISO~8601 and Unix Timestamps.

Converting ISO~8601 strings to Python `datetime` objects is straightforward:

import dateutil.parser
tstr = "2008-01-02T10:20:33-0800"
t = dateutil.parser.parse(tstr)

These objects can then be converted to Unix timestamps:

import time
tval = time.mktime(t.timetuple())

Java programmers can use the Java function `javax.xml.bind.DatatypeConverter.parseDateTime`.

With Python Conversion from Unix timestamp values to ISO~8601 needs to be augmented with an explicit GMT reference, since this is not provided by Python's `datetime` package, which is unaware of UTC offsets:

>>> dt = datetime.datetime.utcfromtimestamp(101106)
>>> dt.isoformat()+"Z"

The conversion can also be performed with the function \emph{strftime} that is present in many programming languages. This function allows conversion to either GMT or local time. Once again, the programmer needs to be cognizant of the need to explicitly reference the UTC offset:

>>> t = 101106
>>> time.strftime("%FT%TZ",time.gmtime(t))                                                                              
>>> time.strftime("%FT%T%z",time.localtime(t))