Pandas - 将 AM/PM 格式更改为 24 小时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42118338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:55:43  来源:igfitidea点击:

Pandas - Change AM/PM format to 24h

pythonpandasdatetime

提问by lte__

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

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

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

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?

但是,这似乎忽略了 AM/PM 标记,并且所有信息都显示为时间在 AM 中,因此对于'10:23:34 PM''10:23:34'作为输出获得的输入,但它应该是'22:23:45'. 我怎样才能解决这个问题?

回答by EdChum

You want %Hnot %I:

你想%H%I

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

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

%Ireturns the 12-hour clock format, you want %Hto return the 24-hour format, see the docs

%I返回 12 小时制时钟格式,您想%H返回 24 小时制格式,请参阅文档

I think you can do this without using applyhere:

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

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

Note this gives you strings rather than a datetime

请注意,这为您提供字符串而不是日期时间