Python datetime to iso string


The ISO 8601 standard defines an internationally recognized format for representing dates and times. ISO 8601 is a date and time format which helps to remove different forms of the day, date, and time conventions across the world. To tackle this uncertainty of various formats ISO sets a format to represent dates “YYYY-MM-DD”.

For example, May 31, 2022, is represented as 2022-05-31.

In this article, we will discuss how to get an ISO 8601 date in string format in python.

Using the .isoformat() method

The .isoformat() method returns a string of date and time values of a python datetime.date object in ISO 8601 format.

Syntax

The syntax of .isoformat() method is as follows.

date.isoformat(sep=’T’,timespec=’auto’)

Where,

  • sep(Optional parameter) − It is a separator character that is to be printed between the date and time fields.

  • timespec(Optional parameter) − It is the format specifier for timespec. The default value is auto.

In this method, we get the current datetime string by using the datetime.now() method which returns the current date and time in time format. This string is then converted into the ISO format by using the .isoformat() method.

Example

In this example code, we get an ISO 8601 date in string format using the .isoformat() method.

from datetime import datetime current_date = datetime.now() print(current_date.isoformat())

Output

The output of the above code is as follows.

2022-05-31T10:29:01.226141

Using the .strftime() method

The strftime() method is provided by the datetime module in python. Here we use the strftime() method to convert a string datetime to datetime. It is also used to convert datetime to epoch.

Epoch is the starting point of time and is platform-dependent. The epoch is January 1, 1970, 00:00:00 (UTC) on Windows and most Unix systems, and leap seconds are not included in the time in seconds since the epoch. We use time.gmtime(0) to get the epoch on a given platform.

Syntax

The syntax of strftime() is described below.

date.strftime(format)

Where, format is used to specify the required format of the output.

In this method, we get the current date and time from the local CPU by using the datetime.now() method. This string is converted into an ISO format string by using the .strftime() method. Here as we know that ISO format is YYYY-MM-DD so we convert it into this format by using the following format code- “%Y-%m-%dT%H:%M:%S.%f%z”.

Example

The following is an example code, to ISO date in string format using the .strftime() method.

from datetime import datetime current_date = datetime.now() print(current_date.strftime('%Y-%m-%dT%H:%M:%S.%f%z'))

Output

The output of the above code is as follows.

2022-09-05T10:35:08.217174

Python datetime to iso string

Updated on 08-Sep-2022 07:14:41

  • Related Questions & Answers
  • Python Pandas - Format Timedelta as ISO 8601
  • Display ISO 8601 standard date in Java
  • How to convert ISO 8601 string to Date/time object in Android?
  • How to convert ISO 8601 String to Date/Time object in Android using Kotlin?
  • How do I format a string using a dictionary in Python 3?
  • How do I get the current date in JavaScript?
  • How to format date string in PowerShell?
  • How do I get the current date and time in JavaScript?
  • How do I re-format datetime in MySQL?
  • How do I get the average string length in MySQL?
  • How do I get the parent directory in Python?
  • How do I do a case insensitive string comparison in Python?
  • How do I get the creation date of a MySQL table?
  • Remove Seconds/ Milliseconds from Date and convert to ISO String?
  • How to get string as date in MySQL with dates as dot format specifier?

The ISO 8601 time format does not store a time zone name, only the corresponding UTC offset is preserved.

To convert a file ctime to an ISO 8601 time string while preserving the UTC offset in Python 3:

>>> import os
>>> from datetime import datetime, timezone
>>> ts = os.path.getctime(some_file)
>>> dt = datetime.fromtimestamp(ts, timezone.utc)
>>> dt.astimezone().isoformat()
'2015-11-27T00:29:06.839600-05:00'

The code assumes that your local timezone is Eastern Time Zone (ET) and that your system provides a correct UTC offset for the given POSIX timestamp (ts), i.e., Python has access to a historical timezone database on your system or the time zone had the same rules at a given date.

If you need a portable solution; use the pytz module that provides access to the tz database:

>>> import os
>>> from datetime import datetime
>>> import pytz  # pip install pytz
>>> ts = os.path.getctime(some_file)
>>> dt = datetime.fromtimestamp(ts, pytz.timezone('America/New_York'))
>>> dt.isoformat()
'2015-11-27T00:29:06.839600-05:00'

The result is the same in this case.

If you need the time zone name/abbreviation/zone id, store it separately.

>>> dt.astimezone().strftime('%Y-%m-%d %H:%M:%S%z (%Z)')
'2015-11-27 00:29:06-0500 (EST)'

Note: no, : in the UTC offset and EST timezone abbreviation is not part of the ISO 8601 time format. It is not unique.

Different libraries/different versions of the same library may use different time zone rules for the same date/timezone. If it is a future date then the rules might be unknown yet. In other words, the same UTC time may correspond to a different local time depending on what rules you use -- saving a time in ISO 8601 format preserves UTC time and the local time that corresponds to the current time zone rules in use on your platform. You might need to recalculate the local time on a different platform if it has different rules.

How do I convert datetime to ISO 8601 in Python?

UTC to ISO 8601 in Python First, get the current UTC datetime by mentioning the timezone. utc attribute in the now() function. Next, use the isoformat() method convert the UTC time to ISO 8601 format.

How do I create an ISO date in Python?

Using the . The . isoformat() method returns a string of date and time values of a python datetime. date object in ISO 8601 format.

How do I convert a datetime to a string in Python?

To convert Python datetime to string, use the strftime() function. The strftime() method is a built-in Python method that returns the string representing date and time using date, time, or datetime object.

What is Z in datetime Python?

List of the Date format codes:.