Movatterモバイル変換


[0]ホーム

URL:


Python Pandas Tutorial

Python Pandas - Timedelta



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 Class

Thepandas.Timedelta class is a powerful tool to represent a duration or the difference between two dates or times. It is equivalent of Python'sdatetime.timedelta object and can be used interchangeably in most cases.

Syntax

Following 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.

Example

Following is the basic example of creating theTimedelta object.

import pandas as pd# Initialize Timedelta with value and unittd = 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:00Data Type of the Resultant Object: <class 'pandas._libs.tslibs.timedeltas.Timedelta'>

Also, you can createTimedelta objects in various ways, such as by passing a string, integer, or by using data offsets. Additionally, Pandas provides a top-level functionto_timedelta() to convert scalar, array, list, or series intoTimedelta type.

Creating Timedelta with a String

You can create a Timedelta object by passing a string that represents a duration.

Example

Here is the example of creating theTimedelta object using the string.

import pandas as pdprint(pd.Timedelta('2 days 2 hours 15 minutes 30 seconds'))

Itsoutput is as follows −

2 days 02:15:30

Creating Timedelta with an Integer

By passing an integer value with the unit, an argument creates aTimedelta object.

Example

This example converts an integer into theTimedelta object.

import pandas as pdprint(pd.Timedelta(6,unit='h'))

Itsoutput is as follows −

0 days 06:00:00

Creating Timedelta with Data Offsets

Data offsets such as - weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds can also be used in construction.

Example

Here is the example −

import pandas as pdprint(pd.Timedelta(days=2))

Itsoutput is as follows −

Creating Timedelta with an Integer2 days 00:00:00

Using pd.to_timedelta() Function

Thepd.to_timedelta function converts a scalar, array, list, or series from a recognizedtimedelta format or value into aTimedelta type. It will construct a Series if the input is a Series, a scalar if the input is scalar-like, or aTimedeltaIndex otherwise.

import pandas as pdprint(pd.Timedelta(days=2))

Itsoutput is as follows −

2 days 00:00:00

Timedelta Operations

You can perform arithmetic operations on Series or DataFrames containingdatetime64[ns] andtimedelta64[ns] data types.

Example − Addition Operation

Let us now create a DataFrame with Timedelta and datetime objects and perform Addition operation on it −

import pandas as pds = 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)

Itsoutput is as follows −

           A      B          C0 2012-01-01 0 days 2012-01-011 2012-01-02 1 days 2012-01-032 2012-01-03 2 days 2012-01-05

Example − Subtraction Operation

Here is the example of subtracting theTimedelta values.

import pandas as pds = 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)

Itsoutput is as follows −

           A      B          C          D0 2012-01-01 0 days 2012-01-01 2012-01-011 2012-01-02 1 days 2012-01-03 2012-01-042 2012-01-03 2 days 2012-01-05 2012-01-07

Timedelta Class Properties and Methods

TheTimedelta object provides various properties and methods that are useful in date-time manipulation.

Properties

Following are the list of attributes of theTimedelta object.

Sr.No.Property & Description
1

Timedelta.asm8

Return a numpy timedelta64 array scalar view.

2

Timedelta.components

Return a components namedtuple-like.

3

Timedelta.days

Returns the days of the timedelta.

4

Timedelta.max

Return the maximum timedelta object.

5

Timedelta.microseconds

Return the microseconds of the timedelta.

6

Timedelta.min

Return the minimum timedelta object.

7

Timedelta.nanoseconds

Return the number of nanoseconds (n), where 0 <= n < 1 microsecond.

8

Timedelta.resolution

Return the resolution of the timedelta.

9

Timedelta.seconds

Return the total hours, minutes, and seconds of the timedelta as seconds.

10

Timedelta.unit

Return the unit of the timedelta.

11

Timedelta.value

Return the underlying value of the timedelta in nanoseconds.

Methods

In the following table you can found the list of method of theTimedelta object.

Sr.No.Method & Description
1

Timedelta.as_unit(unit[, round_ok])

Convert the underlying int64 representation to the given unit.

2

Timedelta.ceil(freq)

Return a new Timedelta ceiled to this resolution.

3

Timedelta.floor(freq)

Return a new Timedelta floored to this resolution.

4

Timedelta.isoformat()

Format the Timedelta as ISO 8601 Duration.

5

Timedelta.round(freq)

Round the Timedelta to the specified resolution.

6

Timedelta.to_pytimedelta()

Convert a pandas Timedelta object into a python datetime.timedelta object.

7

Timedelta.to_timedelta64()

Return a numpy.timedelta64 object with 'ns' precision.

8

Timedelta.to_numpy([dtype, copy])

Convert the Timedelta to a NumPy timedelta64.

9

Timedelta.total_seconds()

Return the total seconds in the duration.

10

Timedelta.view(dtype)

Array view compatibility.

Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp