RFC3339: Simple, canonical date parsing and formatting for Python

By: on May 20, 2010

As part of a customer project some years ago, we wrote an [implementation](http://github.com/tonyg/python-rfc3339) of the interesting parts of RFC [3339](http://www.ietf.org/rfc/rfc3339.txt) for Python. The abstract for the RFC says

> This document defines a date and time format for use in Internet
> protocols that is a profile of the ISO 8601 standard for
> representation of dates and times using the Gregorian calendar.

We needed to be able to robustly transfer timestamps between languages (Javascript and Python, chiefly) without getting tangled up in timezone troubles or complex ambiguous parsing problems.

Our code provides

* simple, standard, robust, cross-language (e.g. Javascript) format for parsing and printing time stamps
* a standard no-frills “UTC” `tzinfo` class and singleton instance
* a standard no-frills fixed-offset `tzinfo` class
* other utilities for helping write robust timezone-aware time manipulation code

Examples

These examples are taken from the doctests/docstrings in the module source itself. See the module documentation for many more informative examples.

Parsing a timestamp, with timezone support and timestamp equivalence:

>>> midnightUTC = parse_datetime(“2008-08-24T00:00:00Z”)
>>> oneamBST = parse_datetime(“2008-08-24T01:00:00+01:00″)
>>> midnightUTC == oneamBST
True

Printing a timestamp:

>>> oneamBST.isoformat()
’2008-08-24T01:00:00+01:00′
>>> parse_datetime(“2008-08-24T00:00:00.123Z”).isoformat()
’2008-08-24T00:00:00.123000+00:00′

Downloading the code

The code is [available on github](http://github.com/tonyg/python-rfc3339/). It’s [MIT-licensed](http://www.opensource.org/licenses/mit-license.php).

* Browse the code [here](http://github.com/tonyg/python-rfc3339)
* Download a [tarball](http://github.com/tonyg/python-rfc3339/tarball/master) of the latest code

You can also install the module directly from github using `pip`:

pip install -e git://github.com/tonyg/python-rfc3339.git#egg=rfc3339

FacebookTwitterGoogle+

2 Comments

  1. jpc says:

    Have you considered TAI64[1]?

  2. tonyg says:

    TAI64 is fine, but not supported natively by Javascript (unlike the RFC3339 profile of ISO8601). It’s also not so human readable.

Post a comment

Your email address will not be published.

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>