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 - Return a components namedtuple-like
Pandas provides the timedelta.components property to return a components namedtuple-like object that breaks down a Timedelta into its individual time units (days, hours, minutes, seconds, etc.).
Basic Usage
First, let's import pandas and create a Timedelta object ?
import pandas as pd
# Create a Timedelta object
timedelta = pd.Timedelta('1 days 10 min 20 s')
print("Timedelta:", timedelta)
# Return a components namedtuple-like
components = timedelta.components
print("Components:", components)
Timedelta: 1 days 00:10:20 Components: Components(days=1, hours=0, minutes=10, seconds=20, milliseconds=0, microseconds=0, nanoseconds=0)
Accessing Individual Components
You can access each component individually using dot notation ?
import pandas as pd
timedelta = pd.Timedelta('2 days 5 hours 30 minutes 45 seconds 500 milliseconds')
components = timedelta.components
print("Days:", components.days)
print("Hours:", components.hours)
print("Minutes:", components.minutes)
print("Seconds:", components.seconds)
print("Milliseconds:", components.milliseconds)
Days: 2 Hours: 5 Minutes: 30 Seconds: 45 Milliseconds: 500
Working with Complex Timedeltas
The components property is useful for complex time durations ?
import pandas as pd
# Create a complex timedelta
td = pd.Timedelta(days=15, hours=23, minutes=59, seconds=59,
milliseconds=999, microseconds=500, nanoseconds=250)
print("Original Timedelta:", td)
print("\nBreakdown:")
comp = td.components
print(f"Days: {comp.days}")
print(f"Hours: {comp.hours}")
print(f"Minutes: {comp.minutes}")
print(f"Seconds: {comp.seconds}")
print(f"Milliseconds: {comp.milliseconds}")
print(f"Microseconds: {comp.microseconds}")
print(f"Nanoseconds: {comp.nanoseconds}")
Original Timedelta: 15 days 23:59:59.999500250 Breakdown: Days: 15 Hours: 23 Minutes: 59 Seconds: 59 Milliseconds: 999 Microseconds: 500 Nanoseconds: 250
Conclusion
The components property provides a convenient way to access individual time units from a Timedelta object. This is useful for detailed time analysis and formatting operations in pandas.
Advertisements
