Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Pandas - ดึงจำนวนวินาทีทั้งหมด (Total Seconds) จาก Timedelta object

เพื่อดึงจำนวนวินาทีทั้งหมด (total seconds) ในระยะเวลาจาก Timedelta object ให้ใช้เมธอด timedelta.total_seconds()

เริ่มต้นด้วยการนำเข้าไลบรารีที่จำเป็น:

import pandas as pd

TimeDeltas เป็นไลบรารี datetime มาตรฐานของ Python ใช้การแทนค่าที่ต่างกัน สร้าง Timedelta object:

timedelta = pd.Timedelta('2 days 11 hours 22 min 25 s 50 ms 45 ns')

แสดง Timedelta:

print("Timedelta...\n", timedelta)

ดึงจำนวนวินาทีทั้งหมด:

timedelta.total_seconds()

ตัวอย่างโค้ดเต็ม

import pandas as pd

# TimeDeltas is Python's standard datetime library uses a different representation timedelta's
# create a Timedelta object
timedelta = pd.Timedelta('2 days 11 hours 22 min 25 s 50 ms 45 ns')

# display the Timedelta
print("Timedelta...\n", timedelta)

# get the total seconds
res = timedelta.total_seconds()

# Return the result i.e. the total seconds in the duration
print("\nTotal seconds...\n", res)

เอาต์พุต

จะได้ผลลัพธ์ดังนี้:

Timedelta... 2 days 11:22:25.050000045
Total seconds... 213745.05