How do I get an ISO 8601 date in string format in Python?

PythonProgrammingServer Side Programming

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
raja
Updated on 08-Sep-2022 07:14:41

Advertisements