Skip to content
Advertisement

How to subtract date and time in Pandas?

I have data from Pandas which was the contents of a CSV file:

Date                Inbound     Outbound
17/10/2019 12:35    5.49E+02    3.95E+03 
17/10/2019 12:40    2.06E+02    3.17E+03 
17/10/2019 12:45    2.06E+02    3.17E+03 
17/10/2019 12:50    2.06E+02    3.17E+03 
17/10/2019 12:55    2.06E+02    3.17E+03 
17/10/2019 13:00    2.06E+02    3.17E+03
....

I aim to convert the column Date from timestamps to time periods in units of minutes, which should result in something like the following:

    Date        Inbound     Outbound
    0           5.49E+02    3.95E+03 
    5           2.06E+02    3.17E+03 
    10          2.06E+02    3.17E+03 
    15          2.06E+02    3.17E+03 
    20          2.06E+02    3.17E+03 
    25          2.06E+02    3.17E+03

Advertisement

Answer

You can use subtract the first timestampe to calculate the difference, then get total_seconds() and convert to minutes:

df['Date'] = pd.to_datetime(df['Date'])

df['Date'] = (df.Date.sub(df.Date.iloc[0])
   .dt.total_seconds().div(60).astype(int)
)

Output:

   Date  Inbound  Outbound
0     0    549.0    3950.0
1     5    206.0    3170.0
2    10    206.0    3170.0
3    15    206.0    3170.0
4    20    206.0    3170.0
5    25    206.0    3170.0
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement