pandas -将AM/PM格式更改为24h [英] Pandas - Change AM/PM format to 24h

查看:116
本文介绍了 pandas -将AM/PM格式更改为24h的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在字符串中以'10:23:34 PM'的格式输入了一些时间,我想将其转换为类似于'22:23:45'的日期时间.我正在使用

I have some time input in the format of '10:23:34 PM' in string and I'd like to convert it to a datetime looking like '22:23:45'. I'm using

datetime = posts['time'].apply(lambda x: datetime.strptime(x, '%I:%M:%S %p').strftime('%I:%M:%S'))

但是,这似乎无视AM/PM标记,所有信息都好像时间在AM一样,对于'10:23:34 PM'输入,我会得到'10:23:34'作为输出,但是应该为'22:23:45'.我该如何解决?

However, this seems to disregard the AM/PM markers, and all the info comes out as if the time was in the AM, ergo for the '10:23:34 PM' input I get '10:23:34' as output, but it should be '22:23:45'. How can I fix this?

推荐答案

您要%H而不是%I:

In [44]:
d='10:23:34 PM'
pd.to_datetime(d).strftime('%H:%M:%S')

Out[44]:
'22:23:34'

%I返回12小时制,您希望%H返回24小时制,请参见

%I returns the 12-hour clock format, you want %H to return the 24-hour format, see the docs

我认为您可以在不使用apply的情况下执行此操作:

I think you can do this without using apply here:

datetime = pd.to_datetime(posts['time']).dt.strftime('%H:%M:%S')

请注意,这给了您字符串而不是日期时间

Note this gives you strings rather than a datetime

这篇关于 pandas -将AM/PM格式更改为24h的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆