rfc3339.py

rfc3339.py is a small script to format date to a rfc 3339 string. This function can be useful if you want to add an Atom feed to you site / project. Grab the file, drop it in your python source code, that's it! The code is in the Public domain.
Related blog post.

How to use it:

>>> import time
>>> timestamp = time.time()
>>> print timestamp
1220939251.89
>>> import datetime
>>> d = datetime.datetime.fromtimestamp(timestamp)
>>> print d
2008-09-08 22:47:31.893205

>>> from rfc3339 import rfc3339

>>> rfc3339(timestamp) # Works with timestamps
'2008-09-08T22:47:31-07:00'

>>> rfc3339(d) # And datetime & date objects
'2008-09-08T22:47:31-07:00'

>>> rfc3339(d, utc=True) # Normalize time to UTC
'2008-09-08T15:47:31Z'
>>> rfc3339(d, utc=True, use_system_timezone=False)
'2008-09-08T22:47:31Z'

Documentation

Wow! I also made some docs! Generated via pydoc rfc3339

Help on module rfc3339:

NAME
    rfc3339

FILE
    rfc3339.py

DESCRIPTION
    The function `rfc3339` formats dates according to the :RFC:`3339`. `rfc3339`
    tries to have as much as possible sensible defaults.

FUNCTIONS
    rfc3339(date, utc=False, use_system_timezone=True)
        Return a string formatted according to the :RFC:`3339`. If called with
        `utc=True`, it normalizes `date` to the UTC date. If `date` does not have
        any timezone information, uses the local timezone::
        
            >>> date = datetime.datetime(2008, 4, 2, 20)
            >>> rfc3339(date, utc=True, use_system_timezone=False)
            '2008-04-02T20:00:00Z'
            >>> rfc3339(date) # doctest: +ELLIPSIS
            '2008-04-02T20:00:00...'
        
        If called with `user_system_time=False` don't use the local timezone if
        `date` does not have timezone informations and consider the offset to UTC
        to be zero::
        
            >>> rfc3339(date, use_system_timezone=False)
            '2008-04-02T20:00:00+00:00'
        
        `date` must be a `datetime.datetime`, `datetime.date` or a timestamp as
        returned by `time.time()`::
        
            >>> rfc3339(0, utc=True, use_system_timezone=False)
            '1970-01-01T00:00:00Z'
            >>> rfc3339(datetime.date(2008, 9, 6), utc=True,
            ...         use_system_timezone=False)
            '2008-09-06T00:00:00Z'
            >>> rfc3339(datetime.date(2008, 9, 6),
            ...         use_system_timezone=False)
            '2008-09-06T00:00:00+00:00'
            >>> rfc3339('foo bar')
            Traceback (most recent call last):
            ...
            TypeError: excepted datetime, got str instead

DATA
    __all__ = ('rfc3339',)
    __author__ = 'Henry Precheur <henry@precheur.org>'
    __license__ = 'Public Domain'
    __version__ = '1'

VERSION
    1

AUTHOR
    Henry Precheur <henry@precheur.org>