Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas pd.Timedelta() function

Pandas pd.Timedelta() function

Pandas Universal Functions Common Pandas functions


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


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

print

(

"=== Create time difference from 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. Creating with keyword arguments

print

(

"n=== Create 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. Creating with a numeric value and unit

print

(

"n=== Create with 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. Converting from datetime.timedelta

print

(

"n=== Convert 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. Viewing Timedelta attributes

print

(

"n=== Timedelta attributes ==="

)

td

=

pd.

Timedelta

(

'3 days 12 hours 30 minutes 45 seconds'

)

print

(

f

"Time difference: {td}"

)

print

(

f

"Total days: {td.days}"

)

print

(

f

"Total seconds: {td.seconds}"

)

print

(

f

"Total microseconds: {td.microseconds}"

)

print

(

f

"Total seconds (with fraction): {td.total_seconds()}"

)

print

(

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:

  1. pd.Timedelta() It supports multiple creation methods: strings, keyword arguments, value+unit, and datetime.timedelta.
  2. The string format is very flexible, supporting '1 days', '2 weeks', '1 days 02:30:45', and more.
  3. 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

print

(

"=== Timestamp and time difference operations ==="

)

ts

=

pd.

Timestamp

(

'2023-01-01 12:00:00'

)

td

=

pd.

Timedelta

(

days

=

5

,

hours

=

3

)

print

(

f

"Timestamp: {ts}"

)

print

(

f

"Time difference: {td}"

)

print

(

f

"ts + td: {ts + td}"

)

print

(

f

"ts - td: {ts - td}"

)

2. Subtracting two timestamps to get a time difference

print

(

"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

print

(

f

"ts1: {ts1}"

)

print

(

f

"ts2: {ts2}"

)

print

(

f

"ts1 - ts2: {tdiff}"

)

print

(

f

"Day difference: {tdiff.days}"

)

print

(

f

"Hour difference: {tdiff.total_seconds() / 3600}"

)

3. Operations between time differences

print

(

"n=== Operations between time differences ==="

)

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 a time difference and a number

print

(

"n=== Time difference 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}"

)

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:

Example 3: Using time differences in a DataFrame

Example

import

pandas

as

pd

import

numpy

as

np

1. Creating a DataFrame with time differences

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'

)

Compute completion time

df

[

'complete_time'

]

=

df

[

'order_time'

]

[

'process_timedelta'

]

print

(

df

)

2. Computing 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. Computing due times

print

(

"n=== Compute due time (assuming orders must be completed within 24 hours) ==="

)

deadline

=

pd.

Timedelta

(

hours

=

24

)

df

[

'deadline'

]

=

df

[

'order_time'

]

df

[

'is_ontime'

]

=

df

[

'complete_time'

]

<

;=

df

[

&

#039;deadline']

print

(

df

[

[

&

#039;order_id', 'order_time', 'complete_time', 'deadline', 'is_ontime']])

4. Filtering overdue orders

print

(

"

;

n

===

Overdue orders

===

"

;

)

late_orders

=

df

[

~

df

[

&

#039;is_ontime']]

print

(

f"

;

Number of overdue orders:

{

len

(

late_orders

)

}

"

;

)

print

(

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:


Notes

Important note:

  • pd.Timedelta It stores a time interval, not a specific point in time.
  • A time difference can be positive (future) or negative (past).
  • The difference between pd.NaT Similarly, there is pd.NaT representing a missing time difference.
  • When using unit parameter, make sure the value type is correct.

  • Pandas Universal Functions Common Pandas functions