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

Why python 2.7 doesn't include Z character (Zulu or zero offset) at the end of UTC datetime object's isoformat string unlike JavaScript?

    >>> datetime.datetime.utcnow().isoformat()

Whereas in javascript

    >>>  console.log(new Date().toISOString()); 

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, timedelta
    class 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()

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.)


Back to homepage or read more recommendations: