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 - Get the seconds from Timedelta object using string input
To extract seconds from a Pandas Timedelta object, use the timedelta.seconds property. This property returns the total seconds component of the timedelta duration.
Creating a Timedelta Object
First, let's create a Timedelta object using string input ?
import pandas as pd
# Create a Timedelta object with string input
timedelta = pd.Timedelta('1 min 30 s')
print("Timedelta object:", timedelta)
Timedelta object: 0 days 00:01:30
Extracting Seconds
Use the seconds property to get the seconds component ?
import pandas as pd
# Create a Timedelta object
timedelta = pd.Timedelta('1 min 30 s')
# Extract seconds using .seconds property
seconds = timedelta.seconds
print("Total seconds:", seconds)
Total seconds: 90
Different String Input Formats
Timedelta accepts various string formats for time input ?
import pandas as pd
# Different string formats
formats = [
'2 hours 15 minutes 45 seconds',
'3h 20m 10s',
'1 day 5 hours 30 minutes',
'45 seconds'
]
for fmt in formats:
td = pd.Timedelta(fmt)
print(f"'{fmt}' ? {td.seconds} seconds")
'2 hours 15 minutes 45 seconds' ? 8145 seconds '3h 20m 10s' ? 12010 seconds '1 day 5 hours 30 minutes' ? 19800 seconds '45 seconds' ? 45 seconds
Important Notes
The seconds property returns only the seconds component (0-86399), not the total duration in seconds. For total seconds, use total_seconds() ?
import pandas as pd
td = pd.Timedelta('1 day 2 hours 30 minutes')
print("Seconds component:", td.seconds)
print("Total seconds:", td.total_seconds())
Seconds component: 9000 Total seconds: 102600.0
Conclusion
Use timedelta.seconds to extract the seconds component from a Timedelta object. For the complete duration in seconds, use total_seconds() instead.
Advertisements
