Generate RFC 3339 timestamp in Python

Yarin picture Yarin · Dec 19, 2011 · Viewed 66.1k times · Source

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

monkut picture monkut · Dec 19, 2011

Timezones are a pain, which is probably why they chose not to include them in the datetime library.

try pytz, it has the tzinfo your looking for: http://pytz.sourceforge.net/

You need to first create the datetime object, then apply the timezone like as below, and then your .isoformat() output will include the UTC offset as desired:

d = datetime.datetime.utcnow()
d_with_timezone = d.replace(tzinfo=pytz.UTC)
d_with_timezone.isoformat()

'2017-04-13T14:34:23.111142+00:00'

Or, just use UTC, and throw a "Z" (for Zulu timezone) on the end to mark the "timezone" as UTC.

d = datetime.datetime.utcnow() # <-- get time in UTC
print d.isoformat("T") + "Z"

'2017-04-13T14:34:23.111142Z'