Free cookie consent management tool by TermsFeed The fromisoformat() method of Python DateTime class | Pythontic.com

The fromisoformat() method of Python DateTime class

Overview:

  • The class method fromisoformat() creates a datetime object as per the string in ISO 8601 format.

  • With the ISO 8601 format several combinations of inputs are possible. Most frequently used ones are often the subset of the following full form: YYYY-MM-DDTHH:MM:YY±hh:mm. The trailing ±hh:mm specifies the UTC offset in hours and minutes.

  • There are also the less used ones like YYYY-WNN, Where W is the prefix and NN is the week number of the year.

  • When the day of a week is specified the format YYYY-WNN-D, W is the prefix and NN is the week number of the year and D is the day of the week.

Example 1:

# Example Python program that creates datetime
# objects from ISO 8601 format strings containing date
# and time information

from datetime import datetime

# Create the date for Christmas day
christmasDay = datetime.fromisoformat("2025-12-25")
print("Christmas day:")
print(christmasDay)

# Local time 3 PM on New year day
timeLocal = datetime.fromisoformat("2025-01-01 15:00")
print("Local time:")
print(timeLocal)

# Specify 2 PM EST on New year day
timeEST = datetime.fromisoformat("2025-01-01T14:00-05:00")
print("EST time:")
print(timeEST)

# Specify 11 AM UTC on New year day
timeUTC = datetime.fromisoformat("2025-01-01T11:00Z")
print("UTC:")
print(timeUTC)
print(type(timeUTC))

Output:

Christmas day:
2025-12-25 00:00:00
Local time:
2025-01-01 15:00:00
EST time:
2025-01-01 14:00:00-05:00
UTC:
2025-01-01 11:00:00+00:00
<class 'datetime.datetime'>

Example 2:

# Example Python program that creates a datetime
# object from an ISO 8601 format string containing week
# information

from datetime import datetime

# Create the first date of a given week
wk = datetime.fromisoformat("2025-W25")
print("First day of the 25th week:")
print(wk)

# Create the nth day of a given week
wk = datetime.fromisoformat("2025-W25-2")
print("Second day of the 25th week:")
print(wk)

Output:

First day of the 25th week:
2025-06-16 00:00:00
Second day of the 25th week:
2025-06-17 00:00:00

 


Copyright 2025 © pythontic.com