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

StackOverflow

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()
"2013-10-29T09:14:03.895210"

Whereas in javascript

>>>  console.log(new Date().toISOString()); 
2013-10-29T09:38:41.341Z

Answer rating: 93

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 datetime

In [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-10 12: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 pytz

In [6]: d = datetime.datetime(2014, 12, 10, 12, 0, 0, tzinfo=pytz.utc)

In [7]: d
Out[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"




Tutorials