ISO 8601

From Simson Garfinkel
Revision as of 19:24, 9 August 2011 by Simson (talk | contribs) (Created page with "Converting between ISO~8601 and Unix Timestamps. Converting ISO~8601 strings to Python `datetime` objects is straightforward: <pre> import dateutil.parser tstr = "2008-01-02T1...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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"
'1970-01-02T04:05:06Z'

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))                                                                              
'1970-01-02T04:05:06Z'
>>> time.strftime("%FT%T%z",time.localtime(t))                                                                          
'1970-01-01T23:05:06-0500'