isoformat() Method Of Time Class In Python

For a datetime.time instance, the isoformat() method returns the time in a format as prescribed by the ISO 8601 standard. The Python example constructs a time instance and prints multiple ISO 8601 formats for the given time.

Time Updated 13 Jul 2019 1 min read

Function Name

isoformat

Function Signature

isoformat(timespec=”auto”)

Parameters

timespec – Defines what components of time to be included in the return value.

Return Value

A string value containing the time with specified precision. Valid values and their meanings are given here.

Parameter ValueFormat of the time string returned
autoEquivalent to seconds
hoursHH:HH
minutesHH:MM
secondsHH:MM:SS
millisecondsHH:MM:sss
microsecondsHH:MM:ssssss

Overview

  • The method isoformat() returns the time as a string in the format as specified by the ISO 8601 standard.

  • The return value can contain a string of minimum length 2, representing HH for hours and of maximum length 15, representing HH:MM:SS:ssssss.
  • In the similar way ISO format of a date object can be obtained using date.isoformat().

Example

python
# ----- Example program to print datetime.date objects in ISO 8601 format

import datetime

# Pass hours, minutes, seconds and microseconds as parameters

pastMidnight    = datetime.time(0, 30, 2, 123456);

timeInISOFormat = pastMidnight.isoformat(timespec="microseconds");

print("Time in ISO format:%s"%timeInISOFormat);

# Display only upto minutes....let other components like seconds and microseconds be truncated

timeInISOFormat = pastMidnight.isoformat(timespec="minutes");

print("Time with up to minutes part:%s"%timeInISOFormat);

Output

Output
Time in ISO format:00:30:02.123456

Time with up to minutes part:00:30