Warm tip: This article is reproduced from serverfault.com, please click

TypeError: cannot astype a datetimelike from [datetime64[ns]] to [timedelta64[D]]

发布于 2020-11-28 02:08:51

So I am trying to calculate the duration between two days but I just want the number of days instead of minutes and seconds for the duration. The code I am using is the following:

df['duration']=df['deadline'].sub(df['created_at'].astype('datetime64[D]'))

However, this gives me sth like : 35 days 12:42:40. But I don't want the "days 12:42:40." Instead, I want to extract the 35 as an interger. So I tried to replace the datetime64[D] with [timedelta64[D], which gave me the TypeError. Is there any way for me to do this?

Questioner
Jiang Yuxin
Viewed
0
K.L.Miller 2020-11-28 11:07:16

The most pythonic and easiest way to solve this problem is to subtract the two series from one another and then access the datetime accessor on the series to retrieve the days.

Here is a quick example.

df = pd.DataFrame({
    'deadline': pd.date_range(start='2020-03-01', end='2020-03-05', periods=5),
    'created_date': pd.date_range(start='2020-01-01', end='2020-01-9', periods=5)
})

df['duration'] = (df.deadline - df.created_date).dt.days