无法将dataframe列转换为24

系统教程 行业动态 更新时间:2024-06-14 17:04:03
无法将dataframe列转换为24-H格式的datetime(Cannot convert dataframe column to 24-H format datetime)

我的数据框中有一个timestamp列,最初是str类型。 一些样本值:

'6/13/2015 6:45:58 AM' '6/13/2015 7:00:37 PM'

我使用以下代码使用此代码将此值转换为24小时格式的datetime:

df['timestampx'] = pd.to_datetime(df['timestamp'], format='%m/%d/%Y %H:%M:%S %p')

而且,我得到了这个结果:

2015-06-13 06:45:58 2015-06-13 07:00:37

这意味着,日期不会以24H格式转换,我也会丢失AM / PM信息。 有帮助吗?

I have a timestamp column in my dataframe which is originally a str type. Some sample values:

'6/13/2015 6:45:58 AM' '6/13/2015 7:00:37 PM'

I use the following code to convert this values into datetime with 24H format using this code:

df['timestampx'] = pd.to_datetime(df['timestamp'], format='%m/%d/%Y %H:%M:%S %p')

And, I obtain this result:

2015-06-13 06:45:58 2015-06-13 07:00:37

That means, the dates are NOT converted with 24H format and I am also loosing the AM/PM info. Any help?

最满意答案

你是在24小时内阅读它,但实际上当前格式不是24小时,而是12小时。 使用后缀(上午/下午)将其读入12小时,如果需要,您可以在24小时后输出。

df = pd.DataFrame(['6/13/2015 6:45:58 AM','6/13/2015 7:00:37 PM'], columns = ['timestamp']) df['timestampx'] = pd.to_datetime(df['timestamp'], format='%m/%d/%Y %I:%M:%S %p') print df timestamp timestampx 0 6/13/2015 6:45:58 AM 2015-06-13 06:45:58 1 6/13/2015 7:00:37 PM 2015-06-13 19:00:37

You're reading it in as a 24 hour time, but really the current format isn't 24 hour time, it's 12 hour time. Read it in as 12 hour with the suffix (AM/PM), then you'll be OK to output in 24 hour time later if need be.

df = pd.DataFrame(['6/13/2015 6:45:58 AM','6/13/2015 7:00:37 PM'], columns = ['timestamp']) df['timestampx'] = pd.to_datetime(df['timestamp'], format='%m/%d/%Y %I:%M:%S %p') print df timestamp timestampx 0 6/13/2015 6:45:58 AM 2015-06-13 06:45:58 1 6/13/2015 7:00:37 PM 2015-06-13 19:00:37

更多推荐

本文发布于:2023-04-24 21:16:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/279a35131c24521e0ac710a81f4458ed.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   dataframe

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!