English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Pandas Timedelta operation example
Time increments are time differences represented in the difference unit, such as days, hours, minutes, seconds. They can be positive or negative.
By passing a string literal, we can create a timedelta object.
We can create Timedelta objects using various parameters as shown below-
import pandas as pd print(pd.Timedelta('2 days 2 hours 15 minutes 30 seconds'))
The running results are as follows:
2 days 02:15:30
By passing an integer value to the unit, the parameter will create a Timedelta object.
import pandas as pd print(pd.Timedelta(6,unit='h'))
The running results are as follows:
0 days 06:00:00
Data offset (for example-week, day, hour, minute, second, millisecond, microsecond, nanosecond) can also be used in construction.
import pandas as pd print(pd.Timedelta(days=2))
The running results are as follows:
2 days 00:00:00
Using pd.to_timedelta, you can convert a scalar, array, list, or sequence from a recognized timedelta format/Value is converted to Timedelta type. If the input is a Series, a Series will be constructed; if the input is a scalar, a scalar will be constructed; otherwise, a TimedeltaIndex will be output.
import pandas as pd print(pd.Timedelta(days=2))
The running results are as follows:
2 days 00:00:00
You can operate on the Series / perform operations on the DataFrame, and by comparing the datetime64 [ns] Series or Timestamps for subtraction operations to construct timedelta64 [ns] Series .
Now let's create a DataFrame with Timedelta and datetime objects and perform some arithmetic operations on it-
import pandas as pd s = pd.Series(pd.date_range('2012-1-1', periods=3, freq='D')) td = pd.Series([pd.Timedelta(days=i) for i in range(3)]) df = pd.DataFrame(dict(A = s, B = td)) print(df)
The running results are as follows:
A B 0 2012-01-01 0 days 1 2012-01-02 1 days 2 2012-01-03 2 days
import pandas as pd s = pd.Series(pd.date_range('2012-1-1', periods=3, freq='D')) td = pd.Series([pd.Timedelta(days=i) for i in range(3)]) df = pd.DataFrame(dict(A = s, B = td)) df['C'] = df['A']+df['B'] print(df)
The running results are as follows:
A B C 0 2012-01-01 0 days 2012-01-01 1 2012-01-02 1 days 2012-01-03 2 2012-01-03 2 days 2012-01-05
import pandas as pd s = pd.Series(pd.date_range('2012-1-1', periods=3, freq='D')) td = pd.Series([pd.Timedelta(days=i) for i in range(3)]) df = pd.DataFrame(dict(A = s, B = td)) df['C'] = df['A']+df['B'] df['D'] = df['C']+df['B'] print(df)
The running results are as follows:
A B C D 0 2012-01-01 0 days 2012-01-01 2012-01-01 1 2012-01-02 1 days 2012-01-03 2012-01-04 2 2012-01-03 2 days 2012-01-05 2012-01-07