To get the current time in UTC in Python 3.2+:

>>> from datetime import datetime, timezone
>>> datetime.now(timezone.utc).isoformat()
'2015-01-27T05:57:31.399861+00:00'

To get local time in Python 3.3+:

>>> from datetime import datetime, timezone
>>> datetime.now(timezone.utc).astimezone().isoformat()
'2015-01-27T06:59:17.125448+01:00'

Explanation: datetime.now(timezone.utc) produces a timezone aware datetime object in UTC time. astimezone() then changes the timezone of the datetime object, to the system's locale timezone if called with no arguments. Timezone aware datetime objects then produce the correct ISO format automatically.

Answer from jfs on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ isoformat-method-of-datetime-class-in-python
Isoformat() Method Of Datetime Class In Python - GeeksforGeeks
October 15, 2021 - # Python3 code to demonstrate # Getting date and time values # in ISO 8601 format # importing datetime module import datetime # Getting today's date and time DateTime_in_ISOFormat = datetime.datetime.now() # Printing Today's date and time in ISO format of # auto value for the format specifier print(DateTime_in_ISOFormat.isoformat("#", "auto")) # Printing Today's date and time format specifier # as hours print(DateTime_in_ISOFormat.isoformat("#", "hours")) # Printing Today's date and time format specifier # as minutes print(DateTime_in_ISOFormat.isoformat("#", "minutes")) # Printing Today's dat
Discussions

python - How to get current isoformat datetime string including the default timezone? - Stack Overflow
When you have an aware datetime object, you can use isoformat() and get the output you need. To make your datetime objects aware, you'll need to subclass tzinfo, like the second example in here, or simpler - use a package that does it for you, like pytz or python-dateutil More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to convert Python's .isoformat() string back into datetime object - Stack Overflow
So in Python 3, you can generate an ISO 8601 date with .isoformat(), but you can't convert a string created by isoformat() back into a datetime object because Python's own datetime directives don't... More on stackoverflow.com
๐ŸŒ stackoverflow.com
datetime - ISO time (ISO 8601) in Python - Stack Overflow
I came across this question when looking for the XSD date time format (xs:dateTime). I needed to remove the microseconds from isoformat. More on stackoverflow.com
๐ŸŒ stackoverflow.com
Add ISO Basic format support to datetime.isoformat() and date.isoformat()
Feature or enhancement Proposal: In additional to the popular ISO 8601 Extended format, there's also an ISO 8601 Basic format for datetimes which is useful for filenames and URL components as i... More on github.com
๐ŸŒ github.com
13
May 11, 2024
๐ŸŒ
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

Top answer
1 of 7
163

To get the current time in UTC in Python 3.2+:

>>> from datetime import datetime, timezone
>>> datetime.now(timezone.utc).isoformat()
'2015-01-27T05:57:31.399861+00:00'

To get local time in Python 3.3+:

>>> from datetime import datetime, timezone
>>> datetime.now(timezone.utc).astimezone().isoformat()
'2015-01-27T06:59:17.125448+01:00'

Explanation: datetime.now(timezone.utc) produces a timezone aware datetime object in UTC time. astimezone() then changes the timezone of the datetime object, to the system's locale timezone if called with no arguments. Timezone aware datetime objects then produce the correct ISO format automatically.

2 of 7
42

You need to make your datetime objects timezone aware. from the datetime docs:

There are two kinds of date and time objects: โ€œnaiveโ€ and โ€œawareโ€. This distinction refers to whether the object has any notion of time zone, daylight saving time, or other kind of algorithmic or political time adjustment. Whether a naive datetime object represents Coordinated Universal Time (UTC), local time, or time in some other timezone is purely up to the program, just like itโ€™s up to the program whether a particular number represents metres, miles, or mass. Naive datetime objects are easy to understand and to work with, at the cost of ignoring some aspects of reality.

When you have an aware datetime object, you can use isoformat() and get the output you need.

To make your datetime objects aware, you'll need to subclass tzinfo, like the second example in here, or simpler - use a package that does it for you, like pytz or python-dateutil

Using pytz, this would look like:

import datetime, pytz
datetime.datetime.now(timezone.utc).isoformat()

You can also control the output format, if you use strftime with the '%z' format directive like

datetime.datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%f%z')
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
Convert Between Isoformat String and datetime in Python | note.nkmk.me
August 22, 2023 - Handle date and time with the datetime module in Python ยท To convert date and time objects to ISO format (ISO 8601) strings, use the isoformat() method on date, time, and datetime objects.
Find elsewhere
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ python-how-to-use-the-datetime-isoformat-method-in-python-398274
How to use the datetime.isoformat method in Python | LabEx
The isoformat() method is a powerful tool provided by the datetime module in Python. It allows you to convert a datetime object into a string representation that follows the ISO 8601 standard.
๐ŸŒ
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.
๐ŸŒ
Pythontic
pythontic.com โ€บ datetime โ€บ datetime โ€บ isoformat
The isoformat() method of datetime class in Python | Pythontic.com
In Python the isoformat() method of datetime class returns the date-time string with the specified separator. If no separator is specified space is printed
๐ŸŒ
Statology
statology.org โ€บ home โ€บ how to work with date and time in iso format in python
How to Work with Date and Time in ISO Format in Python
August 16, 2024 - Pythonโ€™s datetime module can handle these as well: from datetime import datetime import pytz # Create a timezone-aware datetime tz = pytz.timezone('America/New_York') dt_with_tz = tz.localize(datetime(2024, 7, 30, 14, 30)) # Convert to ISO format iso_with_tz = dt_with_tz.isoformat() print(f"ISO string with timezone: {iso_with_tz}") print(type(iso_with_tz)) # Parse ISO string with timezone parsed_dt = datetime.fromisoformat(iso_with_tz) print(f"Parsed datetime with timezone: {parsed_dt}") print(type(parsed_dt))
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.Timestamp.isoformat.html
pandas.Timestamp.isoformat โ€” pandas 3.0.1 documentation
>>> ts = pd.Timestamp('2020-03-14T15:32:52.192548651') >>> ts.isoformat() '2020-03-14T15:32:52.192548651' >>> ts.isoformat(timespec='microseconds') '2020-03-14T15:32:52.192548'
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ isoformat-function-of-datetime-date-class-in-python
Isoformat() Function Of Datetime.date 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"๏ฟฝteTime_in_ISOFormat);
Top answer
1 of 14
1247

Local to ISO 8601:

import datetime
datetime.datetime.now().isoformat()
>>> '2024-08-01T14:38:32.499588'

UTC to ISO 8601:

import datetime
datetime.datetime.now(datetime.timezone.utc).isoformat()
>>> '2024-08-01T04:38:47.731215+00:00'

Local to ISO 8601 without microsecond:

import datetime
datetime.datetime.now().replace(microsecond=0).isoformat()
>>> '2024-08-01T14:38:57'

UTC to ISO 8601 with timezone information (Python 3):

import datetime
datetime.datetime.now(datetime.timezone.utc).isoformat()
>>> '2024-08-01T04:39:06.274874+00:00'

Local to ISO 8601 with timezone information (Python 3):

import datetime
datetime.datetime.now().astimezone().isoformat()
>>> '2024-08-01T14:39:16.698776+10:00'

Local to ISO 8601 with local timezone information without microsecond (Python 3):

import datetime
datetime.datetime.now().astimezone().replace(microsecond=0).isoformat()
>>> '2024-08-01T14:39:28+10:00'

Notice there is a bug when using astimezone() on utcnow(). This gives an incorrect result:

datetime.datetime.utcnow().astimezone().isoformat() #Incorrect result, do not use.

.utcnow() is deprecated, use .now(datetime.timezome.utc) instead.

For Python 2, see and use pytz.

2 of 14
139

ISO 8601 allows a compact representation with no separators except for the T, so I like to use this one-liner to get a quick timestamp string:

>>> datetime.datetime.now(datetime.UTC).strftime("%Y%m%dT%H%M%S.%fZ")
'20180905T140903.591680Z'

If you don't need the microseconds, just leave out the .%f part:

>>> datetime.datetime.now(datetime.UTC).strftime("%Y%m%dT%H%M%SZ")
'20180905T140903Z'

For local time:

>>> datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=-5))).strftime("%Y-%m-%dT%H:%M:%S%:z")
'2018-09-05T14:09:03-05:00'

In general, I recommend you leave the punctuation in. RFC 3339 recommends that style because if everyone uses punctuation, there isn't a risk of things like multiple ISO 8601 strings being sorted in groups on their punctuation. So the one liner for a compliant string would be:

>>> datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
'2018-09-05T14:09:03Z'
๐ŸŒ
Python
bugs.python.org โ€บ issue23332
datetime.isoformat() -> explicitly mark UTC string as such
January 27, 2015 - 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/67521
๐ŸŒ
GitHub
github.com โ€บ python โ€บ cpython โ€บ issues โ€บ 118948
Add ISO Basic format support to datetime.isoformat() and ...
May 11, 2024 - extension-modulesC modules in the Modules dirC modules in the Modules dirstdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancementA feature request or enhancement ... In additional to the popular ISO 8601 Extended format, there's also an ISO 8601 Basic format for datetimes which is useful for filenames and URL components as it avoids characters such as eg.
Published ย  May 11, 2024
Author ย  mohd-akram
๐ŸŒ
PYnative
pynative.com โ€บ home โ€บ python โ€บ python datetime โ€บ python iso 8601 datetime
Python Get ISO 8601 Datetime [4 Ways] โ€“ PYnative
May 27, 2022 - from datetime import datetime, timezone # get current datetime in UTC dt = datetime.now(timezone.utc) # add local timezone information to datetime tz_dt = dt.astimezone() print('current datetime with local timezone:', tz_dt) # Get current iso 8601 format datetime string including the default timezone iso_date = tz_dt.isoformat() print('ISO datetime with local timezone:', iso_date)Code language: Python (python) Run
๐ŸŒ
Python
bugs.python.org โ€บ issue19475
Issue 19475: Add timespec optional flag to datetime isoformat() to choose the precision - Python tracker
November 1, 2013 - 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/63674
๐ŸŒ
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 โ€ฆ
๐ŸŒ
DataCamp
campus.datacamp.com โ€บ courses โ€บ working-with-dates-and-times-in-python โ€บ combining-dates-and-times
Recreating ISO format with strftime() | Python
Print first_start with both .isoformat() and .strftime(); they should match. Have a go at this exercise by completing this sample code. # Import datetime from datetime import datetime # Pull out the start of the first trip first_start = onebike_datetimes[0]['start'] # Format to feed to strftime() fmt = "____" # Print out date with .isoformat(), then with .strftime() to compare print(first_start.isoformat()) print(____)