Where can I find a routine for building an RFC 3339 time?
3 Answers
This was based on the examples on page 10 of the RFC. The only difference is that I am showing a microseconds value of six digits, conformant to Google Drive's timestamps.
from math import floor
def build_rfc3339_phrase(datetime_obj):
datetime_phrase = datetime_obj.strftime('%Y-%m-%dT%H:%M:%S')
us = datetime_obj.strftime('%f')
seconds = datetime_obj.utcoffset().total_seconds()
if seconds is None:
datetime_phrase += 'Z'
else:
# Append: decimal, 6-digit uS, -/+, hours, minutes
datetime_phrase += ('.%.6s%s%02d:%02d' % (
us,
('-' if seconds < 0 else '+'),
abs(int(floor(seconds / 3600))),
abs(seconds % 3600)
))
return datetime_phrase

- 9,673
- 13
- 65
- 105
rfc3339 is very flexible - http://www.ietf.org/rfc/rfc3339.txt - it effectively defines a whole pile of formats. you can generate almost all of them just using the standard python time formatting - http://docs.python.org/3.3/library/datetime.html#strftime-strptime-behavior
however, there is one oddity, and that is they allow (it's optional) a :
between hours and minutes in a numerical timezone offset (%z
). python won't display that, so if you want to include that you need python-rfc3339 or similar.
for parsing rfc3339, simple-date will handle all formats. but since it uses python print routines it cannot handle the :
case above.

- 45,717
- 10
- 93
- 143