Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing datetime column to integer number without loop

Tags:

python

pandas

I have a pandas dataset like this:

user_id      datetime
   1        13 days 21:50:00
   2        0 days 02:05:00
   5        10 days 00:10:00
   7        2 days 01:20:00
   1        3 days 11:50:00
   2        1 days 02:30:00

I want to have a column that contains the mintues, So in this case the result can be :

 user_id      datetime             minutes         
   1        13 days 21:50:00        20030
   2        0 days 02:05:00          125
   5        10 days 00:10:00        14402
   7        2 days 01:20:00          2960
   1        3 days 11:50:00          5030
   2        1 days 02:30:00          1590

Is there any way to do that without loop?

like image 853
ash Avatar asked Aug 22 '26 22:08

ash


2 Answers

Yes, there is a special dt accessor for date/time series:

df['minutes'] = df['datetime'].dt.total_seconds() / 60

If you only want whole minutes, cast the result using .astype(int).

like image 191
John Zwinck Avatar answered Aug 25 '26 12:08

John Zwinck


Here is a way with pd.Timedelta:

df['minutes'] = pd.to_timedelta(df.datetime) / pd.Timedelta(1, 'm')

>>> df
   user_id          datetime  minutes
0        1  13 days 21:50:00  20030.0
1        2   0 days 02:05:00    125.0
2        5  10 days 00:10:00  14410.0
3        7   2 days 01:20:00   2960.0
4        1   3 days 11:50:00   5030.0
5        2   1 days 02:30:00   1590.0

if your datetime column is already of dtype timedelta, you can omit the explicit casting and just use:

df['minutes'] = df.datetime / pd.Timedelta(1, 'm')
like image 29
sacuL Avatar answered Aug 25 '26 11:08

sacuL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!