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