Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the time spent since midnight in dataframe

I have a dataframe which has a column of type Timestamp. I want to find the time elapsed (in seconds) since midnight as a new column. How to do it in a simple way ?

Eg : Input :

samples['time']
2018-10-01 00:00:01.000000000
2018-10-01 00:00:12.000000000

type(samples['time'].iloc[0])

<class 'pandas._libs.tslib.Timestamp'>

Output :

samples['time_elapsed']
1
12
like image 601
Achyuta Aich Avatar asked Sep 12 '25 06:09

Achyuta Aich


1 Answers

Current answers either too complicated or specialized.

samples = pd.DataFrame(data=['2018-10-01 00:00:01', '2018-10-01 00:00:12'], columns=['time'], dtype='datetime64[ns]')

samples['time_elapsed'] = ((samples['time'] - samples['time'].dt.normalize()) / pd.Timedelta('1 second')).astype(int)

print(samples)
                 time  time_elapsed
0 2018-10-01 00:00:01             1
1 2018-10-01 00:00:12            12
  • normalize() removes the time component from the datetime (moves clock back to midnight).
  • pd.Timedelta('1 s') sets the unit of measurement, i.e. number of seconds in the timedelta.
  • .astype(int) casts the decimal number of seconds to int. Use round functionality if that is preferred.
like image 105
Pontus Hultkrantz Avatar answered Sep 13 '25 19:09

Pontus Hultkrantz