Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Pandas - Format Timedelta as ISO 8601
To format Timedelta as ISO 8601, use the timedelta.isoformat() method. The ISO 8601 duration format represents time periods using a standardized string notation starting with "P" for period.
What is ISO 8601 Duration Format?
ISO 8601 duration format uses the pattern P[n]DT[n]H[n]M[n]S where:
- P − Indicates the start of a period
- D − Days
- T − Separates date and time components
- H − Hours
- M − Minutes
- S − Seconds (including fractional seconds)
Creating and Formatting a Timedelta
First, let's create a Timedelta object and format it as ISO 8601 ?
import pandas as pd
# Create a Timedelta object
timedelta = pd.Timedelta('4 days 11 hours 38 min 20 s 35 ms 55 ns')
# Display the Timedelta
print("Timedelta...")
print(timedelta)
# Format as ISO 8601
iso_format = timedelta.isoformat()
# Display the ISO 8601 formatted result
print("\nFormat Timedelta as ISO 8601...")
print(iso_format)
Timedelta... 4 days 11:38:20.035000055 Format Timedelta as ISO 8601... P4DT11H38M20.035000055S
Multiple Examples
Let's see how different Timedelta values are formatted ?
import pandas as pd
# Different Timedelta examples
examples = [
pd.Timedelta('2 days'),
pd.Timedelta('5 hours 30 minutes'),
pd.Timedelta('1 day 2 hours 15 minutes 30 seconds'),
pd.Timedelta('45 minutes 20 seconds 500 milliseconds')
]
for i, td in enumerate(examples, 1):
print(f"Example {i}:")
print(f" Timedelta: {td}")
print(f" ISO 8601: {td.isoformat()}")
print()
Example 1: Timedelta: 2 days 00:00:00 ISO 8601: P2DT0H0M0S Example 2: Timedelta: 0 days 05:30:00 ISO 8601: P0DT5H30M0S Example 3: Timedelta: 1 days 02:15:30 ISO 8601: P1DT2H15M30S Example 4: Timedelta: 0 days 00:45:20.500000 ISO 8601: P0DT0H45M20.5S
Use Cases
ISO 8601 format is particularly useful for:
- API responses − Standardized time duration representation
- Data serialization − Storing durations in databases or JSON
- Cross-platform compatibility − Universal time duration format
Conclusion
Use timedelta.isoformat() to convert Pandas Timedelta objects to ISO 8601 duration format. This provides a standardized string representation suitable for APIs and data interchange.
Advertisements
