Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Convert timedelta to int in a dataframe

People also ask

How do I convert Timedelta to INT?

We can also convert the timedelta to an integer by dividing it by the timedelta of one day or by extracting its integer part using the astype() attribute.

How do you convert Timedelta to seconds?

To get the Total seconds in the duration from the Timedelta object, use the timedelta. total_seconds() method.

What is Timedelta in pandas?

Timedelta. Represents a duration, the difference between two dates or times. Timedelta is the pandas equivalent of python's datetime. timedelta and is interchangeable with it in most cases.


The Series class has a pandas.Series.dt accessor object with several useful datetime attributes, including dt.days. Access this attribute via:

timedelta_series.dt.days

You can also get the seconds and microseconds attributes in the same way.


You could do this, where td is your series of timedeltas. The division converts the nanosecond deltas into day deltas, and the conversion to int drops to whole days.

import numpy as np

(td / np.timedelta64(1, 'D')).astype(int)

Timedelta objects have read-only instance attributes .days, .seconds, and .microseconds.


If the question isn't just "how to access an integer form of the timedelta?" but "how to convert the timedelta column in the dataframe to an int?" the answer might be a little different. In addition to the .dt.days accessor you need either df.astype or pd.to_numeric

Either of these options should help:

df['tdColumn'] = pd.to_numeric(df['tdColumn'].dt.days, downcast='integer')

or

df['tdColumn'] = df['tdColumn'].dt.days.astype('int16')

I think it's much easier way to it with this (where dif is the difference between dates):

dif_In_Days = dif.days