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-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 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'
Answer from Manav Kataria on Stack Overflow
Top answer
1 of 14
189

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-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 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'
2 of 14
90

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

🌐
Python.org
discuss.python.org › python help
Solved--Why does python not support the `Z` suffix for UTC timezone? - Python Help - Discussions on Python.org
January 1, 2024 - We can put Z at the end to express zero timezone according to ISO8601. [ISO 8601 - Wikipedia](https://iso8601 introduction) “2024-01-01T02:32:21Z” is the right format in ISO8601. >>> s = "2024-01-01T02:32:21Z" >>> dt …
Discussions

Add option to output UTC datetimes as "Z" in `.isoformat()`
BPO 46614 Nosy @brettcannon, @abalkin, @merwok, @pganssle, @godlygeek PRs #32041 Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current stat... More on github.com
🌐 github.com
18
February 2, 2022
Parse "Z" timezone suffix in datetime - Ideas - Discussions on Python.org
This is already opened as BPO 35829 but I wanted to ask about it over here for discussion. Problem Statement The function datetime.fromisoformat() parses a datetime in ISO-8601, format: >>> datetime.fromisoformat('2019-08-28T14:34:25.518993+00:00') datetime.datetime(2019, 8, 28, 14, 34, 25, ... More on discuss.python.org
🌐 discuss.python.org
10
August 28, 2019
How to parse ISO 8601 date in Python? - TestMu AI Community
How can I parse an ISO 8601-formatted date and time in Python date-time from isoformat? I need to parse RFC 3339 strings like “2008-09-03T20:56:35.450686Z” into Python’s datetime type. I have found strptime in the Python standard library, but it is not very convenient. More on community.testmuai.com
🌐 community.testmuai.com
0
October 24, 2024
Python's built in datetime.isoformat() does not comply with ISO 8601. Am I doing something wrong?
ISO8601 contains many different valid formats. datetime.isoformat() outputs just one of them. I've written a lib to parse all of ISO8601 that maps cleanly to python standard library: https://github.com/boxed/iso8601 More on reddit.com
🌐 r/learnpython
8
3
December 4, 2015
🌐
Reddit
reddit.com › r/python › psa: as of python 3.11, `datetime.fromisoformat` supports most iso 8601 formats (notably the "z" suffix)
r/Python on Reddit: PSA: As of Python 3.11, `datetime.fromisoformat` supports most ISO 8601 formats (notably the "Z" suffix)
August 28, 2023 -

In Python 3.10 and earlier, datetime.fromisoformat only supported formats outputted by datetime.isoformat. This meant that many valid ISO 8601 strings could not be parsed, including the very common "Z" suffix (e.g. 2000-01-01T00:00:00Z).

I discovered today that 3.11 supports most ISO 8601 formats. I'm thrilled: I'll no longer have to use a third-party library to ingest ISO 8601 and RFC 3339 datetimes. This was one of my biggest gripes with Python's stdlib.

It's not 100% standards compliant, but I think the exceptions are pretty reasonable:

  • Time zone offsets may have fractional seconds.

  • The T separator may be replaced by any single unicode character.

  • Ordinal dates are not currently supported.

  • Fractional hours and minutes are not supported.

https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat

🌐
Python
bugs.python.org › issue46614
Issue 46614: Add option to output UTC datetimes as "Z" in `.isoformat()` - Python tracker
This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/90772
🌐
GitHub
github.com › python › cpython › issues › 90772
Add option to output UTC datetimes as "Z" in `.isoformat()` · Issue #90772 · python/cpython
February 2, 2022 - python / cpython Public · There was an error while loading. Please reload this page. Notifications · You must be signed in to change notification settings · Fork 34.3k · Star 72.1k · New issueCopy link · New issueCopy link · Open · Open · Add option to output UTC datetimes as "Z" in .isoformat()#90772 ·
Author   pganssle
🌐
Note.nkmk.me
note.nkmk.me › home › python
Convert Between Isoformat String and datetime in Python | note.nkmk.me
August 22, 2023 - To convert a basic format string to an extended format, first convert the basic format string to a datetime object, and then use the isoformat() method to obtain the extended format string. As mentioned above, use fromisoformat() for Python 3.11 and later, and strptime() for earlier versions.
Find elsewhere
🌐
Python.org
discuss.python.org › ideas
Parse "Z" timezone suffix in datetime - Ideas - Discussions on Python.org
August 28, 2019 - This is already opened as BPO 35829 but I wanted to ask about it over here for discussion. Problem Statement The function datetime.fromisoformat() parses a datetime in ISO-8601, format: >>> datetime.fromisoformat('2019-08-28T14:34:25.518993+00:00') datetime.datetime(2019, 8, 28, 14, 34, 25, 518993, tzinfo=datetime.timezone.utc) The timezone offset in my example is +00:00, i.e. UTC.
🌐
Python documentation
docs.python.org › 3 › library › datetime.html
datetime — Basic date and time types
The datetime module supplies classes for manipulating dates and times. While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation. ... Skip to the format codes. ... General calendar related functions. ... Time access and conversions. ... Concrete time zones representing the IANA time zone database.
🌐
GeeksforGeeks
geeksforgeeks.org › isoformat-method-of-datetime-class-in-python
Isoformat() Method Of Datetime Class In Python - GeeksforGeeks
October 15, 2021 - Example 2: In the below example, the isoformat() function has been called on today's date and time and it returns the same today's date and time string in ISO 8601 format. ... # Python3 code to demonstrate # Getting date and time values # in ISO 8601 format # importing datetime and time module import datetime import time # Getting today's date and time todays_Date = datetime.datetime.now() # Calling the isoformat() function over the # today's date and time DateTime_in_ISOFormat = todays_Date.isoformat() # Printing Today's date and time in ISO format print("Today's date and time in ISO Format: %s" % DateTime_in_ISOFormat)
🌐
Python.org
discuss.python.org › ideas
Parse "Z" timezone suffix in datetime - Page 2 - Ideas - Discussions on Python.org
February 25, 2020 - Most have been said here already, just wanted to add that I also arrived at this page after receiving JSON data from a JavaScript application. Also, using dateutil gives a slightly different result. Compare: import dateutil.parser as dt date_time_obj = dt.parse('2020-02-25T13:13:43.913Z') date_time_obj # out: datetime.datetime(2020, 2, 25, 13, 13, 43, 913000, tzinfo=tzutc()) date_time_obj2 = datetime.fromisoformat('2020-02-25T13:13:43.913Z'.replace('Z', '+00:00')) date_time_obj2 # out: dateti...
🌐
Joetsoi
joetsoi.github.io › fromisoformat-django-json-encoder-utc-datetimes
Avoid fromisoformat when parsing UTC date times serialized by DjangoJSONEncoder
class DjangoJSONEncoder(json.JSONEncoder): def default(self, o): # See "Date Time String Format" in the ECMA-262 specification. if isinstance(o, datetime.datetime): r = o.isoformat() if o.microsecond: r = r[:23] + r[26:] if r.endswith("+00:00"): r = r[:-6] + "Z" return r This makes sense as we're dealing with JSON here instead of the specifics of python's fromisoformat implementation.
🌐
TestMu AI Community
community.testmuai.com › ask a question
How to parse ISO 8601 date in Python? - TestMu AI Community
October 24, 2024 - How can I parse an ISO 8601-formatted date and time in Python date-time from isoformat? I need to parse RFC 3339 strings like “2008-09-03T20:56:35.450686Z” into Python’s datetime type. I have found strptime in the Pytho…
🌐
Pythontic
pythontic.com › datetime › datetime › isoformat
The isoformat() method of datetime class in Python | Pythontic.com
The isoformat() method of datetime class returns a date and time string which contains the following information: Date · Time · UTC offset to corresponding time zone · as specified in the standard ISO 8601. The separator character will be printed between the date and time fields.
🌐
Educative
educative.io › answers › what-is-dateisoformat-in-python
What is date.isoformat() in Python?
This isoformat() function belongs to the datetime module in Python. It converts the Date object value into a string in ISO format. It follows the ISO 8601, or YYYY-MM-DD, format.
🌐
IncludeHelp
includehelp.com › python › datetime-isoformat-method-with-example.aspx
Python datetime isoformat() Method with Example
April 22, 2023 - ## importing datetime class from datetime import datetime import pytz ## Naive object isoformat() example x = datetime.today() print("Normal format:",x) d = x.isoformat() print("ISO 8601 format:", d) print("ISO 8601 format without separator 'T':", x.isoformat(sep=' ')) print() ## Microsecond is not 0 here x = datetime(2020, 10, 1, 12, 12, 12, 3400) print("ISO 8601 format:", x.isoformat()) print("ISO format without separator 'T':", x.isoformat(sep=' ')) print() ## Microsecond is 0 here x = datetime(200,10,12,1,1,1) print("Date 200/10/12 1:1:1 in ISO 8601 format:", x.isoformat()) print() ## Awar
🌐
Delft Stack
delftstack.com › home › api › python › python datetime.isoformat
Python datetime.isoformat() Method | Delft Stack
January 30, 2023 - Python datetime.isoformat() method is an efficient way of finding a string of date, time, and UTC offset corresponding to the time zone in ISO 8601 format.
🌐
LinkedIn
linkedin.com › pulse › what-do-z-mean-timestamp-format-omar-ismail
What do T and Z mean in timestamp format ?
September 16, 2021 - The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC). ... TIMESTAMP has a range of ‘1970-01-01 00:00:01’ UTC to ‘2038-01-19 03:14:07’ UTC.