datetime – Python 3 How to format to yyyy-mm-ddThh:mm:ssZ

datetime – Python 3 How to format to yyyy-mm-ddThh:mm:ssZ

Try datetime library

import datetime

output_date =

For more information, refer to the Python Documentation.

Be careful. Just be cause a date can be formatted to look like UTC, doesnt mean its accurate.

In ISO 8601, Z is meant to designate zulu time or UTC (+00:00). While local times are typically designated by their offset from UTC. Even worse, these offsets can change throughout a year due to Daylight Saving Time (DST).

So unless you live in England in the winter or Iceland in the summer, chances are, you arent lucky enough to be working with UTC locally, and your timestamps will be completely wrong.


from datetime import datetime, timezone

# a naive datetime representing local time
naive_dt =

# incorrect, local (MST) time made to look like UTC (very, very bad)
>>> naive_dt.strftime(%Y-%m-%dT%H:%M:%SZ)
2020-08-27T20:57:54Z   # actual UTC == 2020-08-28T02:57:54Z

# so well need an aware datetime (taking your timezone into consideration)
# NOTE: I imagine this works with DST, but I havent verified

aware_dt = naive_dt.astimezone()

# correct, ISO-8601 (but not UTC)
>>> aware_dt.isoformat(timespec=seconds)

# lets get the time in UTC
utc_dt = aware_dt.astimezone(timezone.utc)

# correct, ISO-8601 and UTC (but not in UTC format)
>>> utc_dt.isoformat(timespec=seconds)

# correct, UTC format (this is what you asked for)
>>> date_str = utc_dt.isoformat(timespec=seconds)
>>> date_str.replace(+00:00, Z)

# Perfect UTC format
>>> date_str = utc_dt.isoformat(timespec=milliseconds)
>>> date_str.replace(+00:00, Z)

I just wanted to illustrate some things above, there are much simpler ways:

from datetime import datetime, timezone

def utcformat(dt, timespec=milliseconds):
    convert datetime to string in UTC format (YYYY-mm-ddTHH:MM:SS.mmmZ)
    iso_str = dt.astimezone(timezone.utc).isoformat(T, timespec)
    return iso_str.replace(+00:00, Z)

def fromutcformat(utc_str, tz=None):
    iso_str = utc_str.replace(Z, +00:00)
    return datetime.fromisoformat(iso_str).astimezone(tz)

now =

# default with milliseconds (2020-08-28T02:57:54.640Z)

# without milliseconds (2020-08-28T02:57:54Z)
print(utcformat(now, timespec=seconds))

>>> utc_str1 = 2020-08-28T04:35:35.455Z
>>> dt = fromutcformat(utc_string)
>>> utc_str2 = utcformat(dt)
>>> utc_str1 == utc_str2

# it even converts naive local datetimes correctly (as of Python 3.8)
>>> now =
>>> utc_string = utcformat(now)

>>> converted = fromutcformat(utc_string)
>>> now.astimezone() - converted

datetime – Python 3 How to format to yyyy-mm-ddThh:mm:ssZ

Thanks to skaul05 I managed to get the code I needed, its

date =

Leave a Reply

Your email address will not be published. Required fields are marked *