简体   繁体   中英

How convert an int64 to minutes ? Python Pandas

I would like to transform this column (format int64) to a minutes format to do calculation

Duration(min)
10
30
5
15
5

I tried this:

df['Duration(min)'] = pd.to_datetime(df['Duration(min)'], format='%H%M')

But I have ValueError: time data '5' does not match format '%H%M' (match)

You need to use pd.to_timedelta here.

pd.to_timedelta(df['Duration(min)'], unit='min')

0   0 days 00:10:00
1   0 days 00:30:00
2   0 days 00:05:00
3   0 days 00:15:00
4   0 days 00:05:00
Name: Duration(min), dtype: timedelta64[ns]

unit -> 'm' / 'minute' / 'min' / 'minutes' / 'T' all are shorthand for minutes .

Using pd.to_datetime with strftime -

pd.to_datetime(df.Duration(min), unit='m').dt.strftime('%H:%M')

Output-

0    00:10
1    00:30
2    00:05
3    00:15
4    00:05
dtype: object

Why %H%M when all you have is minutes? Try format='%M'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM