将字符串解析为日期时间,同时考虑 pandas 中的AM/PM [英] Parsing string to datetime while accounting for AM/PM in pandas
问题描述
我正在尝试解析此格式的字符串"2018-07-07 04-AM"
使用strftime格式将日期时间设置为pandas datetime.但是,在我看来,该格式无法识别AM
和PM
之间的区别.
I am trying to parse a string in this format "2018 - 07 - 07 04 - AM"
to pandas datetime using strftime format. However, It seems to me the format doesn't recognize the difference between AM
and PM
.
这是我尝试过的:
pd.to_datetime("2018 - 07 - 07 04 - PM", format='%Y - %m - %d %H - %p').timestamp()
Out[4]: 1530936000.0
pd.to_datetime("2018 - 07 - 07 04 - AM", format='%Y - %m - %d %H - %p').timestamp()
Out[5]: 1530936000.0
pd.to_datetime("2018 - 07 - 07 04 - PM", format='%Y - %m - %d %H - %p').timestamp()
Out[4]: 1530936000.0
pd.to_datetime("2018 - 07 - 07 04 - AM", format='%Y - %m - %d %H - %p').timestamp()
Out[5]: 1530936000.0
请注意,上述两个字符串中的AM
和PM
有何不同,但返回了相同的timeStamp.
Notice how the AM
and PM
are different in the above two strings, yet the same timeStamp is returned.
熊猫版本:0.23.3
Pandas version: 0.23.3
Python版本:3.5.4
Python version: 3.5.4
推荐答案
由于要解析12小时时间格式,因此需要%I
而不是%H
,否则%p
说明符无效
Since you're parsing a 12-hour time format, you will need %I
instead of %H
, otherwise the %p
specifier has no effect.
pd.to_datetime("2018 - 07 - 07 04 - PM", format='%Y - %m - %d %I - %p')
Timestamp('2018-07-07 16:00:00')
此行为记录在文档中:>
This behaviour is documented in the docs:
与
strptime()
函数一起使用时,%p
指令仅影响 如果使用%I
指令解析小时,则为输出小时字段.
When used with the
strptime()
function, the%p
directive only affects the output hour field if the%I
directive is used to parse the hour.
这篇关于将字符串解析为日期时间,同时考虑 pandas 中的AM/PM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!