Pandas pd.Timedelta() function
pd.Timedelta() is a function in the Pandas library used toCreate a time differencefunction. It represents the duration between two points in time and can be used for datetime addition and subtraction.
Timedelta is a powerful tool for working with time durations, commonly used to compute the difference between two dates, add or subtract a specific length of time, and similar scenarios.
Word meaning: Timedelta It combines "time" and "delta", meaning "time increment" - the duration of a period of time.
Basic syntax and parameters
pd.Timedelta() is a top-level function in the Pandas library used to create time difference objects.
Syntax format
pd.Timedelta(value, unit='ns', **kwargs)
Parameter Description
| Parameters | Type | Required | Description | Default value |
|---|---|---|---|---|
| value | str, int, float, datetime.timedelta | Optional | The time difference value to convert. | None |
| unit | String | Optional | Units when value is numeric: 'D' (day), 'h' (hour), 'm' (minute), 's' (second), 'ms' (millisecond), 'us' (microsecond), 'ns' (nanosecond). | 'ns' |
| days | Integers | Optional | Number of days. | 0 |
| hours | Integers | Optional | Number of hours. | 0 |
| minutes | Integers | Optional | Number of minutes. | 0 |
| seconds | Integers | Optional | Number of seconds. | 0 |
| milliseconds | Integers | Optional | Number of milliseconds. | 0 |
| microseconds | Integers | Optional | Number of microseconds. | 0 |
| nanoseconds | Integers | Optional | Number of nanoseconds. | 0 |
Return value description
- Return Value: Returns a Timedelta object representing a time interval.
- effect: Can be used for timestamp addition/subtraction, or to compute the difference between two points in time.
Example
Let us thoroughly master pd.Timedelta() through a series of examples from simple to complex.
Example 1: Basic usage - creating a time difference
Example
import
pandas
as
pd
1. Creating a Timedelta from a string
(
"=== Create time difference from string ==="
)
td1
=
pd.
Timedelta
(
'1 days'
)
(
f
"pd.Timedelta('1 days'): {td1}"
)
td2
=
pd.
Timedelta
(
'2 hours 30 minutes'
)
(
f
"pd.Timedelta('2 hours 30 minutes'): {td2}"
)
td3
=
pd.
Timedelta
(
'1 days 02:30:45'
)
(
f
"pd.Timedelta('1 days 02:30:45'): {td3}"
)
td4
=
pd.
Timedelta
(
'2 weeks'
)
(
f
"pd.Timedelta('2 weeks'): {td4}"
)
2. Creating with keyword arguments
(
"n=== Create with keyword arguments ==="
)
td5
=
pd.
Timedelta
(
days
=
5
,
hours
=
10
,
minutes
=
30
)
(
f
"pd.Timedelta(days=5, hours=10, minutes=30): {td5}"
)
td6
=
pd.
Timedelta
(
hours
=
1.5
)
(
f
"pd.Timedelta(hours=1.5): {td6}"
)
3. Creating with a numeric value and unit
(
"n=== Create with value and unit ==="
)
td7
=
pd.
Timedelta
(
10
,
unit
=
'D'
)
(
f
"pd.Timedelta(10, unit='D'): {td7}"
)
td8
=
pd.
Timedelta
(
30
,
unit
=
'm'
)
(
f
"pd.Timedelta(30, unit='m'): {td8}"
)
4. Converting from datetime.timedelta
(
"n=== Convert from datetime.timedelta ==="
)
import
datetime
dt_td
=
datetime
.
timedelta
(
days
=
3
,
hours
=
6
)
td9
=
pd.
Timedelta
(
dt_td
)
(
f
"From datetime.timedelta: {td9}"
)
5. Viewing Timedelta attributes
(
"n=== Timedelta attributes ==="
)
td
=
pd.
Timedelta
(
'3 days 12 hours 30 minutes 45 seconds'
)
(
f
"Time difference: {td}"
)
(
f
"Total days: {td.days}"
)
(
f
"Total seconds: {td.seconds}"
)
(
f
"Total microseconds: {td.microseconds}"
)
(
f
"Total seconds (with fraction): {td.total_seconds()}"
)
(
f
"Converted to hours: {td.total_seconds() / 3600}"
)
Result:
=== 字符串创建时间差 ===
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 analysis:
pd.Timedelta()It supports multiple creation methods: strings, keyword arguments, value+unit, and datetime.timedelta.- The string format is very flexible, supporting '1 days', '2 weeks', '1 days 02:30:45', and more.
total_seconds()The method returns the total number of seconds (including the fractional part).
Example 2: Time difference operations
Example
import
pandas
as
pd
import
numpy
as
np
1. Adding and subtracting a time difference from a timestamp
(
"=== Timestamp and time difference operations ==="
)
ts
=
pd.
Timestamp
(
'2023-01-01 12:00:00'
)
td
=
pd.
Timedelta
(
days
=
5
,
hours
=
3
)
(
f
"Timestamp: {ts}"
)
(
f
"Time difference: {td}"
)
(
f
"ts + td: {ts + td}"
)
(
f
"ts - td: {ts - td}"
)
2. Subtracting two timestamps to get a time difference
(
"n=== Subtract two timestamps ==="
)
ts1
=
pd.
Timestamp
(
'2023-01-15 18:00:00'
)
ts2
=
pd.
Timestamp
(
'2023-01-10 09:00:00'
)
tdiff
=
ts1 - ts2
(
f
"ts1: {ts1}"
)
(
f
"ts2: {ts2}"
)
(
f
"ts1 - ts2: {tdiff}"
)
(
f
"Day difference: {tdiff.days}"
)
(
f
"Hour difference: {tdiff.total_seconds() / 3600}"
)
3. Operations between time differences
(
"n=== Operations between time differences ==="
)
td1
=
pd.
Timedelta
(
days
=
2
)
td2
=
pd.
Timedelta
(
hours
=
12
)
(
f
"td1: {td1}"
)
(
f
"td2: {td2}"
)
(
f
"td1 + td2: {td1 + td2}"
)
(
f
"td1 - td2: {td1 - td2}"
)
(
f
"td1 * 2: {td1 * 2}"
)
(
f
"td1 / 2: {td1 / 2}"
)
4. Operations between a time difference and a number
(
"n=== Time difference and numeric operations ==="
)
td
=
pd.
Timedelta
(
hours
=
10
)
(
f
"10 hours * 3 = {td * 3}"
)
(
f
"10 hours / 2 = {td / 2}"
)
(
f
"10 hours // 3 = {td // 3}"
)
Result:
=== 时间戳与时间差运算 ===
时间戳: 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 analysis:
- Adding a time difference to a timestamp gives a new timestamp.
- Subtracting two timestamps gives a time difference.
- Time differences can be added to and subtracted from each other.
- A time difference can be multiplied or divided by a number.
Example 3: Using time differences in a DataFrame
Example
import
pandas
as
pd
import
numpy
as
np
1. Creating a DataFrame with time differences
(
"=== 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'
)
Compute completion time
df
[
'complete_time'
]
=
df
[
'order_time'
]
- df
[
'process_timedelta'
]
(
df
)
2. Computing order processing duration statistics
(
"n=== Processing duration statistics ==="
)
total_time
=
df
[
'process_timedelta'
]
.
sum
(
)
avg_time
=
df
[
'process_timedelta'
]
.
mean
(
)
(
f
"Total processing time: {total_time}"
)
(
f
"Average processing time: {avg_time}"
)
3. Computing due times
(
"n=== Compute due time (assuming orders must be completed within 24 hours) ==="
)
deadline
=
pd.
Timedelta
(
hours
=
24
)
df
[
'deadline'
]
=
df
[
'order_time'
]
- deadline
df
[
'is_ontime'
]
=
df
[
'complete_time'
]
<
;=
df
[
&
#039;deadline']
print
(
df
[
[
'order_id', 'order_time', 'complete_time', 'deadline', 'is_ontime']])
4. Filtering overdue orders
(
"
;
n
===
Overdue orders
===
"
;
)
late_orders
=
df
[
~
df
[
&
#039;is_ontime']]
(
f"
;
Number of overdue orders:
{
len
(
late_orders
)
}
"
;
)
(
late_orders
[
[
&
#039;order_id', 'complete_time', 'deadline']])
Result:
=== 订单处理时间分析 ===
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 analysis:
pd.to_timedelta()Numeric values can be converted to Timedelta.- Time differences can easily be added to or subtracted from timestamps.
- You can easily compute statistics such as total processing time and average processing time.
Notes
Important note:
pd.Timedelta It stores a time interval, not a specific point in time.pd.NaT Similarly, there is pd.NaT representing a missing time difference.unit parameter, make sure the value type is correct.
Common Pandas functions