I have two different dates and I want to know the difference in seconds between them.
My data:
id date1 date2 date3 1 2017-03-03T02:38:30.544000 2017-03-03T02:30:21 2017-03-03T02:45:21
I want to add two column to my data frame:
date_first_sec= date1-date2 date_last_sec= date3-date2
My code:
import datetime as dt df.date1= dt.datetime(df.date1) df.date2= dt.datetime(df.date2) df.date3= dt.datetime(df.date3) df['date_first_sec']= (df.date1- df.date2).total_seconds() df['date_last_sec']= (df.date3- df.date2).total_seconds()
This is the error:
TypeError: cannot convert the series to <class 'int'>
Advertisement
Answer
Use .dt.total_seconds()
Ex:
df = pd.DataFrame([{"date1": "2017-03-03T02:38:30.544000", "date2":"2017-03-03T02:30:21", 'date3': "2017-03-03T02:45:21"}]) df.date1= pd.to_datetime(df.date1) df.date2= pd.to_datetime(df.date2) df.date3= pd.to_datetime(df.date3) df['date_first_sec']= (df.date1 - df.date2).dt.total_seconds() df['date_last_sec']= (df.date3 - df.date2).dt.total_seconds() print(df)
Output:
date1 date2 ... date_first_sec date_last_sec 0 2017-03-03 02:38:30.544 2017-03-03 02:30:21 ... 489.544 900.0 [1 rows x 5 columns]