Python Pandas 中的时间格式

Time formatting in Python Pandas

我有一个 Excel 文件,时间格式为 mm:ss.0。我在 Excel 中将其格式化为 [h]:mm:ss;@。如何在 Pandas 中完成此操作?

Time : 58:44.1 in mm:ss.0 format 在格式化后产生结果 7:58:44 in [h]:mm:ss;@ format in Excel .

例如:

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

您可以使用矢量化 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

您可以看到 Desired Output 的 dtype 不是 datetime.time:

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

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