在Pandas数据框中解析日期时间

3

enter image description here

我在Dataframe中有一个类型为'object'的结账列,格式为'2017-08-04T23:31:19.000+02:00'。 但我想要它的格式如图所示。 请问有人能帮我吗?
谢谢:)
2个回答

7

您应该能够将对象列转换为日期时间列,然后使用内置的 datetime 函数。

# create an intermediate column that we won't store on the DataFrame
checkout_as_datetime = pd.to_datetime(df['checkout'])

# Add the desired columns to the dataframe
df['checkout_date'] = checkout_as_datetime.dt.date
df['checkout_time'] = checkout_as_datetime.dt.time

但是,如果您的目标不是将这些特定的新列写到某个地方,而是用它们进行其他计算,那么最简单的方法可能就是覆盖原始列,并从中使用datetime方法。

df['checkout'] = pd.to_datetime(df['checkout'])
df['checkout'].dt.date  # to access the date

2
我还没有测试过这个,但大致上应该是这样的:
 df['CheckOut_date'] = pd.to_datetime(df["CheckOut_date"].dt.strftime('%Y-%m-%d'))
 df['CheckOut_time'] = pd.to_datetime(df["CheckOut_time"].dt.strftime('%H:%m:%s'))

看起来你在strftime调用中漏掉了CheckOut_date的日期。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接