Python 3.x 如何使用python将特定值的时间转换为00:00:00
我有一个数据集,有一个输入和日期、时间。 我只想将输入列中包含的特定值的时间转换为00:00:00,其他时间将按原样显示 我尝试了一个代码,它给了我00:00:00的特定值,但其他时间显示为NaT 有人能帮我解决这个错误吗 我的代码:Python 3.x 如何使用python将特定值的时间转换为00:00:00,python-3.x,pandas,time,Python 3.x,Pandas,Time,我有一个数据集,有一个输入和日期、时间。 我只想将输入列中包含的特定值的时间转换为00:00:00,其他时间将按原样显示 我尝试了一个代码,它给了我00:00:00的特定值,但其他时间显示为NaT 有人能帮我解决这个错误吗 我的代码: df['time_diff']= pd.to_datetime(df['date'] + " " + df['time'], format='%d/%m/%Y %H:%M:%S', dayfirst=True) mask =
df['time_diff']= pd.to_datetime(df['date'] + " " + df['time'],
format='%d/%m/%Y %H:%M:%S', dayfirst=True)
mask = df['x3'].eq(5)
df['Duration'] = np.where(df['x3']== 5, df['time_diff'], np.datetime64('NaT') )
df['Duration'] = df['time_diff'].sub(df['Duration']).dt.total_seconds().div(3600)
然后它给了我这个输出:
日期时间x3持续时间
2018年10月3日6:15:00南
10/3/2018 6:45:00 5 00:00:00
2018年10月3日7:45:00南
2018年3月10日9:00:00南
2018年10月3日9:25:00南
2018年10月3日9:30:00南
2018年10月3日11:00:00南
2018年10月3日11:30:00南
2018年10月3日13:30:00南
10/3/2018 13:50:00 5 00:00:00
2018年3月10日15:00:00南
2018年10月3日15:25:00南
2018年10月3日16:25:00南
2018年3月10日18:00:00南
2018年10月3日19:00:00南
2018年10月3日19:30:00南
2018年10月3日20:00:00南
2018年10月3日22:05:00南
10/3/2018 22:15:00 5 00:00:00
2018年10月3日23:40:00南
10/4/2018 6:58:00 5 00:00:00
2018年4月10日13:00:00南
2018年4月10日16:00:00南
2018年4月10日17:00:00 0 NaN
用于按条件创建新列-使用0时间增量
并将列时间转换为时间增量:
df['Duration'] = np.where(df['x3'].eq(5), np.timedelta64(0), pd.to_timedelta(df['time']))
print (df)
date time x3 Duration
0 10/3/2018 6:15:00 0 06:15:00
1 10/3/2018 6:45:00 5 00:00:00
2 10/3/2018 7:45:00 0 07:45:00
3 10/3/2018 9:00:00 0 09:00:00
4 10/3/2018 9:25:00 0 09:25:00
5 10/3/2018 9:30:00 0 09:30:00
6 10/3/2018 11:00:00 0 11:00:00
7 10/3/2018 11:30:00 0 11:30:00
8 10/3/2018 13:30:00 0 13:30:00
9 10/3/2018 13:50:00 5 00:00:00
10 10/3/2018 15:00:00 0 15:00:00
11 10/3/2018 15:25:00 0 15:25:00
12 10/3/2018 16:25:00 0 16:25:00
13 10/3/2018 18:00:00 0 18:00:00
14 10/3/2018 19:00:00 0 19:00:00
15 10/3/2018 19:30:00 0 19:30:00
16 10/3/2018 20:00:00 0 20:00:00
17 10/3/2018 22:05:00 0 22:05:00
18 10/3/2018 22:15:00 5 00:00:00
19 10/3/2018 23:40:00 0 23:40:00
20 10/4/2018 6:58:00 5 00:00:00
21 10/4/2018 13:00:00 0 13:00:00
22 10/4/2018 16:00:00 0 16:00:00
23 10/4/2018 17:00:00 0 17:00:00
非常感谢您的快速回复。这就是我所期待的。