Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset) Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset) python python

Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset)


Option: isoformat()

Python's datetime does not support the military timezone suffixes like 'Z' suffix for UTC. The following simple string replacement does the trick:

In [1]: import datetimeIn [2]: d = datetime.datetime(2014, 12, 10, 12, 0, 0)In [3]: str(d).replace('+00:00', 'Z')Out[3]: '2014-12-10 12:00:00Z'

str(d) is essentially the same as d.isoformat(sep=' ')

See: Datetime, Python Standard Library

Option: strftime()

Or you could use strftime to achieve the same effect:

In [4]: d.strftime('%Y-%m-%dT%H:%M:%SZ')Out[4]: '2014-12-10T12:00:00Z'

Note: This option works only when you know the date specified is in UTC.

See: datetime.strftime()


Additional: Human Readable Timezone

Going further, you may be interested in displaying human readable timezone information, pytz with strftime %Z timezone flag:

In [5]: import pytzIn [6]: d = datetime.datetime(2014, 12, 10, 12, 0, 0, tzinfo=pytz.utc)In [7]: dOut[7]: datetime.datetime(2014, 12, 10, 12, 0, tzinfo=<UTC>)In [8]: d.strftime('%Y-%m-%d %H:%M:%S %Z')Out[8]: '2014-12-10 12:00:00 UTC'


Python datetime objects don't have time zone info by default, and without it, Python actually violates the ISO 8601 specification (if no time zone info is given, assumed to be local time). You can use the pytz package to get some default time zones, or directly subclass tzinfo yourself:

from datetime import datetime, tzinfo, timedeltaclass simple_utc(tzinfo):    def tzname(self,**kwargs):        return "UTC"    def utcoffset(self, dt):        return timedelta(0)

Then you can manually add the time zone info to utcnow():

>>> datetime.utcnow().replace(tzinfo=simple_utc()).isoformat()'2014-05-16T22:51:53.015001+00:00'

Note that this DOES conform to the ISO 8601 format, which allows for either Z or +00:00 as the suffix for UTC. Note that the latter actually conforms to the standard better, with how time zones are represented in general (UTC is a special case.)


The following javascript and python scripts give identical outputs. I think it's what you are looking for.

JavaScript

new Date().toISOString()

Python

from datetime import datetimedatetime.utcnow().isoformat()[:-3]+'Z'

The output they give is the utc (zelda) time formatted as an ISO string with a 3 millisecond significant digit and appended with a Z.

2019-01-19T23:20:25.459Z