如何使用python从timedelta变量中删除秒和微秒。我有以下数据框,我想删除秒。
df['Duration'] = ['03:12:37.771200','06:52:24.764500','13:19:57.325200','15:01:07.000200','04:05:06.722200','01:10:07.456200']
答案 0 :(得分:5)
将round
方法与'T'
分开使用
df['Duration'] = pd.to_timedelta(df['Duration']).round('T')
print(df)
Duration
0 03:13:00
1 06:52:00
2 13:20:00
3 15:01:00
4 04:05:00
5 01:10:00
您也可以使用floor
df['Duration'] = pd.to_timedelta(df['Duration']).floor('T')
print(df)
Duration
0 03:12:00
1 06:52:00
2 13:19:00
3 15:01:00
4 04:05:00
5 01:10:00
答案 1 :(得分:1)
如果需要从timedelta转换为numpy array
然后转换为timedelta64[m]
的秒数:
df['Duration'] = df['Duration'].values.astype("timedelta64[m]")
dur = ['03:12:37.771200','06:52:24.764500','13:19:57.325200',
'15:01:07.000200','04:05:06.722200','01:10:07.456200']
df = pd.DataFrame({'Duration':dur})
df['Duration'] = pd.to_timedelta(df['Duration']).values.astype("timedelta64[m]")
print (df)
Duration
0 03:12:00
1 06:52:00
2 13:19:00
3 15:01:00
4 04:05:00
5 01:10:00