Timedelta in Pandas represents a duration, or the difference between two dates or times, expressed in units such as days, hours, minutes, or seconds. They are useful for performing arithmetic operations on datetime objects and can be both positive and negative duration's.
Pandas Timedelta ClassThe pandas.Timedelta class is a powerful tool to represent a duration or the difference between two dates or times. It is equivalent of Python's datetime.timedelta object and can be used interchangeably in most cases.
SyntaxFollowing is the syntax of the class −
class pandas.Timedelta(value=<object object>, unit=None, **kwargs)
Where,
value − Accepts the any of the following time object: Timedelta, timedelta, np.timedelta64, str, or int.
unit − It is a optional parameter specifies the unit of the input if the input is an integer. Supported units include: 'W', 'D', 'days', 'hours', 'minutes', 'seconds', 'milliseconds', 'microseconds', 'nanoseconds'.
**kwargs − Accepts keyword arguments like days, seconds, microseconds, milliseconds, minutes, hours, and weeks.
Following is the basic example of creating the Timedelta object.
import pandas as pd # Initialize Timedelta with value and unit td = pd.Timedelta(1, "d") print(td) print('Data Type of the Resultant Object:',type(td))
Following is the output of the above code −
1 days 00:00:00 Data Type of the Resultant Object: <class 'pandas._libs.tslibs.timedeltas.Timedelta'>
Also, you can create Timedelta objects in various ways, such as by passing a string, integer, or by using data offsets. Additionally, Pandas provides a top-level function to_timedelta() to convert scalar, array, list, or series into Timedelta type.
Creating Timedelta with a StringYou can create a Timedelta object by passing a string that represents a duration.
ExampleHere is the example of creating the Timedelta object using the string.
import pandas as pd print(pd.Timedelta('2 days 2 hours 15 minutes 30 seconds'))
Its output is as follows −
2 days 02:15:30Creating Timedelta with an Integer
By passing an integer value with the unit, an argument creates a Timedelta object.
ExampleThis example converts an integer into the Timedelta object.
import pandas as pd print(pd.Timedelta(6,unit='h'))
Its output is as follows −
0 days 06:00:00Creating Timedelta with Data Offsets
Data offsets such as - weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds can also be used in construction.
ExampleHere is the example −
import pandas as pd print(pd.Timedelta(days=2))
Its output is as follows −
Creating Timedelta with an Integer 2 days 00:00:00Using pd.to_timedelta() Function
The pd.to_timedelta function converts a scalar, array, list, or series from a recognized timedelta format or value into a Timedelta type. It will construct a Series if the input is a Series, a scalar if the input is scalar-like, or a TimedeltaIndex otherwise.
import pandas as pd print(pd.Timedelta(days=2))
Its output is as follows −
2 days 00:00:00Timedelta Operations
You can perform arithmetic operations on Series or DataFrames containing datetime64[ns] and timedelta64[ns] data types.
Example − Addition OperationLet us now create a DataFrame with Timedelta and datetime objects and perform Addition operation 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)) df['C']=df['A']+df['B'] print(df)
Its output is 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-05Example − Subtraction Operation
Here is the example of subtracting the Timedelta values.
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)
Its output is 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-07Timedelta Class Properties and Methods
The Timedelta object provides various properties and methods that are useful in date-time manipulation.
PropertiesFollowing are the list of attributes of the Timedelta object.
Sr.No. Property & Description 1Timedelta.asm8
Return a numpy timedelta64 array scalar view.
2Timedelta.components
Return a components namedtuple-like.
3Timedelta.days
Returns the days of the timedelta.
4Timedelta.max
Return the maximum timedelta object.
5Timedelta.microseconds
Return the microseconds of the timedelta.
6Timedelta.min
Return the minimum timedelta object.
7Timedelta.nanoseconds
Return the number of nanoseconds (n), where 0 <= n < 1 microsecond.
8Timedelta.resolution
Return the resolution of the timedelta.
9Timedelta.seconds
Return the total hours, minutes, and seconds of the timedelta as seconds.
10Timedelta.unit
Return the unit of the timedelta.
11Timedelta.value
Return the underlying value of the timedelta in nanoseconds.
MethodsIn the following table you can found the list of method of the Timedelta object.
Sr.No. Method & Description 1Timedelta.as_unit(unit[, round_ok])
Convert the underlying int64 representation to the given unit.
2Timedelta.ceil(freq)
Return a new Timedelta ceiled to this resolution.
3Timedelta.floor(freq)
Return a new Timedelta floored to this resolution.
4Timedelta.isoformat()
Format the Timedelta as ISO 8601 Duration.
5Timedelta.round(freq)
Round the Timedelta to the specified resolution.
6Timedelta.to_pytimedelta()
Convert a pandas Timedelta object into a python datetime.timedelta object.
7Timedelta.to_timedelta64()
Return a numpy.timedelta64 object with 'ns' precision.
8Timedelta.to_numpy([dtype, copy])
Convert the Timedelta to a NumPy timedelta64.
9Timedelta.total_seconds()
Return the total seconds in the duration.
10Timedelta.view(dtype)
Array view compatibility.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4