Pandas pd.Timedelta() Function
pd.Timedelta()is used in the Pandas library tocreate time deltas.This function represents the duration between two time points and can be used for datetime addition and subtraction operations.
Timedelta is a powerful tool for handling time duration, commonly used in scenarios such as calculating the difference between two dates, adding or subtracting specific time lengths, etc.
Word Meaning: TimedeltaIt is a combination of "time" and "delta" (amount of change), meaning "time increment", i.e., the duration length of a period of time.
Basic Syntax and Parameters
pd.Timedelta()It is a top-level function of the Pandas library, used to create time delta objects.
Syntax Format
pd.Timedelta(value, unit='ns', **kwargs)
Parameter Description
| Parameter | Type | Required | Description | Default Value |
|---|---|---|---|---|
| value | String, int, float, datetime.timedelta | Optional | The time delta value to convert. | None |
| unit | String | Optional | Unit when value is a number: 'D' (days), 'h' (hours), 'm' (minutes), 's' (seconds), 'ms' (milliseconds), 'us' (microseconds), 'ns' (nanoseconds). | 'ns' |
| days | Integer | Optional | Number of days. | 0 |
| hours | Integer | Optional | Number of hours. | 0 |
| minutes | Integer | Optional | Number of minutes. | 0 |
| seconds | Integer | Optional | Number of seconds. | 0 |
| milliseconds | Integer | Optional | Number of milliseconds. | 0 |
| microseconds | Integer | Optional | Number of microseconds. | 0 |
| nanoseconds | Integer | Optional | Number of nanoseconds. | 0 |
Return Value Description
- Return Value: Returns a Timedelta object, representing the time interval.
- Effect: Can be used for timestamp addition and subtraction operations, or to calculate the difference between two time points.
Examples
Let us thoroughly master, through a series of examples from simple to complex,pd.Timedelta()its usage.
Example 1: Basic Usage - Creating a Time Delta
Examples
# 1. Create Timedelta using a string
print("=== Creating Time Delta with String ===")
td1 = pd.Timedelta('1 days')
print(f"pd.Timedelta('1 days'): {td1}")
td2 = pd.Timedelta('2 hours 30 minutes')
print(f"pd.Timedelta('2 hours 30 minutes'): {td2}")
td3 = pd.Timedelta('1 days 02:30:45')
print(f"pd.Timedelta('1 days 02:30:45'): {td3}")
td4 = pd.Timedelta('2 weeks')
print(f"pd.Timedelta('2 weeks'): {td4}")
# 2. Create using keyword arguments
print("n=== Creating with Keyword Arguments ===")
td5 = pd.Timedelta(days=5, hours=10, minutes=30)
print(f"pd.Timedelta(days=5, hours=10, minutes=30): {td5}")
td6 = pd.Timedelta(hours=1.5)
print(f"pd.Timedelta(hours=1.5): {td6}")
# 3. Create using numeric value and unit
print("n=== Creating with Numeric Value and Unit ===")
td7 = pd.Timedelta(10, unit='D')
print(f"pd.Timedelta(10, unit='D'): {td7}")
td8 = pd.Timedelta(30, unit='m')
print(f"pd.Timedelta(30, unit='m'): {td8}")
# 4. Convert from datetime.timedelta
print("n=== Converting from datetime.timedelta ===")
import datetime
dt_td = datetime.timedelta(days=3, hours=6)
td9 = pd.Timedelta(dt_td)
print(f"From datetime.timedelta: {td9}")
# 5. View Timedelta attributes
print("n=== Timedelta Attributes ===")
td = pd.Timedelta('3 days 12 hours 30 minutes 45 seconds')
print(f"Time delta: {td}")
print(f"Total days: {td.days}")
print(f"Total seconds: {td.seconds}")
print(f"Total microseconds: {td.microseconds}")
print(f"Total seconds (including decimal part): {td.total_seconds()}")
print(f"Converted to hours: {td.total_seconds() / 3600}")
Output:
=== 字符串创建时间差 ===
pd.Timedelta('1 days'): 1 days, 0:00:00
pd.Timedelta('2 hours 30 minutes'): 0 days, 2:30:00
pd.Timedelta('1 days 02:30:45'): 1 days 02:30:45
pd.Timedelta('2 weeks'): 14 days, 0:00:00
=== 关键字参数创建 ===
pd.Timedelta(days=5, hours=10, minutes=30): 5 days 10:30:00
pd.Timedelta(hours=1.5): 0 days, 01:30:00
=== 数值和单位创建 ===
pd.Timedelta(10, unit='D'): 10 days, 0:00:00
pd.Timedelta(30, unit='m'): 0 days, 0:30:00
=== 从 datetime.timedelta 转换 ===
从 datetime.timedelta: 3 days 06:00:00
=== Timedelta 属性 ===
时间差: 3 days 12:30:45
总天数: 3
总秒数: 45045
总微秒数: 45000
总秒数 (含小数): 303045.0
84.17916666666667
Code Explanation:
pd.Timedelta()Multiple creation methods are supported: string, keyword arguments, numeric + unit, datetime.timedelta.- The string format is very flexible, supporting '1 days', '2 weeks', '1 days 02:30:45', etc.
total_seconds()The method returns the total number of seconds (including the decimal part).
Example 2: Time Delta Operations
Examples
import numpy as np
# 1. Add/subtract timestamp and time delta
print("=== Timestamp and Time Delta Operations ===")
ts = pd.Timestamp('2023-01-01 12:00:00')
td = pd.Timedelta(days=5, hours=3)
print(f"Timestamp: {ts}")
print(f"Time delta: {td}")
print(f"ts + td: {ts + td}")
print(f"ts - td: {ts - td}")
# 2. Subtract two timestamps to get the time delta
print("n=== Subtracting Two Timestamps ===")
ts1 = pd.Timestamp('2023-01-15 18:00:00')
ts2 = pd.Timestamp('2023-01-10 09:00:00')
tdiff = ts1 - ts2
print(f"ts1: {ts1}")
print(f"ts2: {ts2}")
print(f"ts1 - ts2: {tdiff}")
print(f"Days difference: {tdiff.days}")
print(f"Hours difference: {tdiff.total_seconds() / 3600}")
# 3. Operations between time deltas
print("n=== Operations Between Time Deltas ===")
td1 = pd.Timedelta(days=2)
td2 = pd.Timedelta(hours=12)
print(f"td1: {td1}")
print(f"td2: {td2}")
print(f"td1 + td2: {td1 + td2}")
print(f"td1 - td2: {td1 - td2}")
print(f"td1 * 2: {td1 * 2}")
print(f"td1 / 2: {td1 / 2}")
# 4. Operations between time delta and numeric value
print("n=== Time Delta and Numeric Operations ===")
td = pd.Timedelta(hours=10)
print(f"10 hours * 3 = {td * 3}")
print(f"10 hours / 2 = {td / 2}")
print(f"10 hours // 3 = {td // 3}")
Output:
=== 时间戳与时间差运算 === 时间戳: 2023-01-01 12:00:00 时间差: 5 days 03:00:00 ts + td: 2023-01-06 15:00:00 ts - td: 2022-12-27 09:00:00 === 两个时间戳相减 === ts1: 2023-01-15 18:00:00 ts2: 2023-01-10 09:00:00 ts1 - ts2: 5 days 09:00:00 天数差: 5 小时差: 129.0 === 时间差之间的运算 === td1: 2 days, 0:00:00 td2: 12:00:00 td1 + td2: 2 days 12:00:00 td1 - td2: 1 day, 12:00:00 td1 * 2: 4 days, 0:00:00 td1 / 2: 1 day, 0:00:00 === 时间差与数值运算 === 10小时 * 3 = 1 day, 3:00:00 10小时 / 2 = 5:00:00 10小时 // 3 = 3:20:00
Code Explanation:
- Adding a time delta to a timestamp yields a new timestamp.
- Subtracting two timestamps yields a time delta.
- Time deltas can be added to and subtracted from each other.
- Time deltas can be multiplied and divided by numeric values.
Example 3: Using Time Delta in DataFrame
Examples
import numpy as np
# 1. Create a DataFrame with time delta
print("=== Order Processing Time Analysis ===")
# Simulate order data
df = pd.DataFrame({
'order_id': ['A001', 'A002', 'A003', 'A004', 'A005'],
'order_time': pd.date_range('2023-01-01 09:00', periods=5, freq='2H'),
'process_time_min': [30, 45, 60, 20, 90]
})
# Convert processing time to Timedelta
df['process_timedelta'] = pd.to_timedelta(df['process_time_min'], unit='m')
# Calculate completion time
df['complete_time'] = df['order_time'] + df['process_timedelta']
print(df)
# 2. Calculate order processing duration statistics
print("n=== Processing Duration Statistics ===")
total_time = df['process_timedelta'].sum()
avg_time = df['process_timedelta'].mean()
print(f"Total processing time: {total_time}")
print(f"Average processing time: {avg_time}")
# 3. Calculate due time
print("n=== Calculate Due Time (assuming the order must be completed within 24 hours) ===")
deadline = pd.Timedelta(hours=24)
df['deadline'] = df['order_time'] + deadline
df['is_ontime'] = df['complete_time'] <= df['deadline']
print(df[['order_id', 'order_time', 'complete_time', 'deadline', 'is_ontime']])
# 4. Filter overdue orders
print("n===Overdue orders===")
late_orders = df[~df['is_ontime']]
print(f"Number of overdue orders:{len(late_orders)}")
print(late_orders[['order_id', 'complete_time', 'deadline']])
Output:
=== 订单处理时间分析 ===
order_id order_time process_time_min complete_time
0 A001 2023-01-01 09:00:00 30 2023-01-01 09:30:00
1 A002 2023-01-01 11:00:00 45 2023-01-01 11:45:00
2 A003 2023-01-01 13:00:00 60 2023-01-01 14:00:00
3 A004 2023-01-01 15:00:00 20 2023-01-01 15:20:00
4 A005 2023-01-01 17:00:00 90 2023-01-01 18:30:00
=== 处理时长统计 ===
总处理时间: 0 days 04:05:00
平均处理时间: 0 days 00:49:00
=== 计算到期时间(假设订单需要在24小时内完成)===
order_id order_time complete_time deadline is_ontime
0 A001 2023-01-01 09:00:00 2023-01-01 09:30:00 2023-01-02 09:00:00 True
1 A002 2023-01-01 11:00:00 2023-01-01 11:45:00 2023-01-02 11:00:00 True
2 A003 2023-01-01 13:00:00 2023-01-01 14:00:00 2023-02-01 13:00:00 True
3 A004 2023-01-01 15:00:00 2023-01-01 15:20:00 2023-02-01 15:00:00 True
4 A005 2023-01-01 17:00:00 2023-01-01 18:30:00 2023-02-01 17:00:00 True
=== 超时订单 ===
超时订单数: 0
Code Explanation:
pd.to_timedelta()Numeric values can be converted to Timedelta.- Time deltas can be conveniently added to or subtracted from timestamps.
- Statistics such as total processing time and average processing time can be conveniently calculated.
Notes
Important Notes:
pd.TimedeltaIt stores time intervals, not specific points in time.- Time deltas can be positive (future) or negative (past).
- and
pd.NaTSimilarly, there ispd.NaTwhich represents a missing time delta.- When using the
unitparameter, ensure the numeric type is correct.
Other Extensions
Pandas Common Functions