YouTip LogoYouTip

Pandas Pd Timedelta

[![Image 1: Pandas General Functions](#) Pandas Common Functions](#) * * * `pd.Timedelta()` is a function in the Pandas library used for **creating time differences**. It represents the duration between two time points and can be used for date and time arithmetic operations. Timedelta is a powerful tool for handling time duration, commonly used for calculating the difference between two dates, adding or subtracting specific time lengths, and other scenarios. **Word Meaning**: `Timedelta` is a combination of "time" and "delta" (change), meaning "time increment", i.e., the continuous length 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 | Parameter | Type | Required | Description | Default Value | | --- | --- | --- | --- | --- | | value | string, int, float, datetime.timedelta | Optional | The time difference value to convert. | None | | unit | string | Optional | The unit when value is numeric: '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 a time interval. * **Effect**: Can be used for timestamp arithmetic operations, or calculating the difference between two time points. * * * ## Examples Let's thoroughly master the usage of `pd.Timedelta()` through a series of examples from simple to complex. ### Example 1: Basic Usage - Creating Time Difference ## Example import pandas as pd # 1. Create Timedelta using string print("=== Create time difference using 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=== Create using 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=== Create using 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=== 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. View 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 decimal): {td.total_seconds()}") print(f"Convert to hours: {td.total_seconds() / 3600}") **Output:** === Create time difference using string === 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=== Create using keyword arguments === pd.Timedelta(days=5, hours=10, minutes=30): 5 days 10:30:00 pd.Timedelta(hours=1.5): 0 days, 01:30:00=== Create using numeric value and unit === pd.Timedelta(10, unit='D'): 10 days, 0:00:00 pd.Timedelta(30, unit='m'): 0 days, 0:30:00=== Convert from datetime.timedelta ===From datetime.timedelta: 3 days 06:00:00=== Timedelta attributes ===Time difference: 3 days 12:30:45Total days: 3Total seconds: 45045Total microseconds: 45000Total seconds (with decimal): 303045.084.17916666666667 **Code Analysis:** 1. `pd.Timedelta()` supports multiple creation methods: string, keyword arguments, numeric value + unit, datetime.timedelta. 2. The string format is very flexible, supporting '1 days', '2 weeks', '1 days 02:30:45', etc. 3. The `total_seconds()` method returns the total number of seconds (including the decimal part). ### Example 2: Time Difference Operations ## Example import pandas as pd import numpy as np # 1. Add and subtract Timedelta with Timestamp print("=== Timestamp and Timedelta operations ===") ts = pd.Timestamp('2023-01-01 12:00:00') td = pd.Timedelta(days=5, hours=3) print(f"Timestamp: {ts}") print(f"Timedelta: {td}") print(f"ts + td: {ts + td}") print(f"ts - td: {ts - td}") # 2. Subtract two Timestamps to get Timedelta 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"Days difference: {tdiff.days}") print(f"Hours difference: {tdiff.total_seconds() / 3600}") # 3. Operations between Timedeltas print("n=== Operations between Timedeltas ===") 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 Timedelta and numeric values print("n=== Timedelta 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:**
← Pandas Series Dt MonthPandas Pd Date Range β†’