Yarin Yarin - 3 months ago 16
Python Question

Generate RFC 3339 timestamp in Python

I'm trying to generate an RFC 3339 UTC timestamp in Python. So far I've been able to do the following:

>>> d = datetime.datetime.now()
>>> print d.isoformat('T')
2011-12-18T20:46:00.392227


My problem is with setting the UTC offset.

According to the docs, the classmethod
datetime.now([tz])
, takes an optional
tz
argument where
tz must be an instance of a class tzinfo subclass
, and
datetime.tzinfo
is
an abstract base class for time zone information objects.


This is where I get lost- How come tzinfo is an abstract class, and how am I supposed to implement it?




(NOTE: In PHP it's as simple as
timestamp = date(DATE_RFC3339);
, which is why I can't understand why Python's approach is so convoluted...)

Answer

Further down in the same doc that you linked to, it explains how to implement it, giving some examples, including full code for a UTC class (representing UTC), a FixedOffset class (representing a timezone with a fixed offset from UTC, as opposed to a timezone with DST and whatnot), and a few others.