我当前正在构建一个跟踪登录/退出登录的程序,数据以“ 5:00 AM”这样的字符串形式导出,我使用以下代码将数据从字符串转换为datetime64 [ns] < / p>
df = pd.DataFrame({ 'LoginTime' : ["10:00PM", "5:00AM", "11:00PM","7:00AM"],
'Logout Time' : ["6:00AM","2:00PM", "5:00AM", "5:00PM"]})
for c in df.columns:
if c == 'LoginTime':
df['LoginTime'] = pd.to_datetime(df['LoginTime'], format='%I:%M%p')
elif c == 'Logout Time':
df['Logout Time'] = pd.to_datetime(df['Logout Time'], format='%I:%M%p')
输出结果如下:
LoginTime Logout Time
0 1900-01-01 22:00:00 1900-01-01 06:00:00
1 1900-01-01 05:00:00 1900-01-01 14:00:00
2 1900-01-01 23:00:00 1900-01-01 05:00:00
3 1900-01-01 07:00:00 1900-01-01 17:00:00
LoginTime datetime64[ns]
Logout Time datetime64[ns]
代码按预期工作,并将字符串更改为时间格式,但是,我注意到格式为1/1/1900 10:00:00 PM,我想知道是否有办法只获取时间,例如这10:00:00 PM不会影响数据类型为datetime64 [ns],因为我必须为“登录” /“登录”创建验证
预先感谢
答案 0 :(得分:0)
将dt.strftime
转换为datetime
格式后,尝试使用:
df = pd.DataFrame({'LoginTime':['1/1/1900 10:00:00 PM', '1/2/2018 05:00:00 AM']})
LoginTime
0 1/1/1900 10:00:00 PM
1 1/2/2018 05:00:00 AM
df['LoginTime'] = pd.to_datetime(df['LoginTime']).dt.strftime('%I:%M %p')
LoginTime
0 10:00 PM
1 05:00 AM