简体   繁体   中英

Time formatting in Python Pandas

I've an Excel file having time in mm:ss.0 format. I formatted this into [h]:mm:ss;@ in Excel. How can this be done in Pandas?

Time : 58:44.1 in mm:ss.0 format yields a result 7:58:44 in [h]:mm:ss;@ format in Excel after formatting.

For example:

Input      Desired Output
58:44.1    7:58:44
07:53.3    8:07:53
46:59.6    9:47:00
20:14.0    10:20:14
50:58.7    11:50:59
19:50.0    12:19:50
41:53.5    13:41:53

You can slice the string using vectorised str method, then construct datetime using to_datetime from this passing the format string and add a TimedeltaIndex to it and then access the time component using dt.time :

In [199]:
df['Desired Output'] = (pd.to_datetime(df['Input'].str[:-2], format='%M:%S') + pd.TimedeltaIndex(np.arange(7, 7 + len(df)), 'h')).dt.time
df

Out[199]:
     Input Desired Output
0  58:44.1       07:58:44
1  07:53.3       08:07:53
2  46:59.6       09:46:59
3  20:14.0       10:20:14
4  50:58.7       11:50:58
5  19:50.0       12:19:50
6  41:53.5       13:41:53

You can see that the dtype for Desired Output is not datetime.time :

In [201]:
df['Desired Output'].iloc[0]

Out[201]:
datetime.time(7, 58, 44)

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