Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Convert datetime column into seconds [duplicate]

Tags:

I have a date column (called 'Time') which contains days/hours/mins etc (timedelta). I have created a new column in my dataframe and I want to convert the 'Time' column into seconds and put it in the new column for each row.

Does anyone have any pointers? All I can find on the internet is how to convert your column, not create a new column and convert another one.

Thank you in advance!

like image 856
ScoutEU Avatar asked Dec 06 '16 10:12

ScoutEU


People also ask

How do I convert datetime to seconds in Python?

To convert a datetime to seconds, subtracts the input datetime from the epoch time. For Python, the epoch time starts at 00:00:00 UTC on 1 January 1970. Subtraction gives you the timedelta object. Use the total_seconds() method of a timedelta object to get the number of seconds since the epoch.

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.


2 Answers

I think you need total_seconds:

print (df['col'].dt.total_seconds()) 

Sample:

df = pd.DataFrame({'date1':pd.date_range('2015-01-01', periods=3),                    'date2':pd.date_range('2015-01-01 02:00:00', periods=3, freq='23H')})  print (df)        date1               date2 0 2015-01-01 2015-01-01 02:00:00 1 2015-01-02 2015-01-02 01:00:00 2 2015-01-03 2015-01-03 00:00:00  df['diff'] = df['date2'] - df['date1'] df['seconds'] = df['diff'].dt.total_seconds()  print (df)        date1               date2     diff  seconds 0 2015-01-01 2015-01-01 02:00:00 02:00:00   7200.0 1 2015-01-02 2015-01-02 01:00:00 01:00:00   3600.0 2 2015-01-03 2015-01-03 00:00:00 00:00:00      0.0 

df['diff'] = df['date2'] - df['date1'] df['diff'] = df['diff'].dt.total_seconds()  print (df)        date1               date2    diff 0 2015-01-01 2015-01-01 02:00:00  7200.0 1 2015-01-02 2015-01-02 01:00:00  3600.0 2 2015-01-03 2015-01-03 00:00:00     0.0 

If need cast to int:

df['diff'] = df['date2'] - df['date1'] df['diff'] = df['diff'].dt.total_seconds().astype(int)  print (df)        date1               date2  diff 0 2015-01-01 2015-01-01 02:00:00  7200 1 2015-01-02 2015-01-02 01:00:00  3600 2 2015-01-03 2015-01-03 00:00:00     0 
like image 141
jezrael Avatar answered Sep 29 '22 21:09

jezrael


Let's assume your DataFrame's name is df.

If you want to create a new column with the seconds you should do the following:

df['newColumn'] = df['Time'].dt.total_seconds() 
like image 23
Manuel Salgueiro Avatar answered Sep 29 '22 19:09

Manuel Salgueiro