UPDATE 2021
In Python 3.2 timezone
was added to the datetime module allowing you to easily assign a timezone to UTC.
>>> import datetime
>>> n = datetime.datetime.now(datetime.timezone.utc)
>>> n.isoformat()
'2021-07-13T15:28:51.818095+00:00'
previous answer:
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’