告诉Python哪是天哪是月

2024-04-26 04:09:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含大量时间数据的数据框,如下所示:

2018年8月1日14:02:03

我使用以下代码将其转换为日期时间:

df["Date"]=pd.to_datetime((df["Date"]))

它给了我这个: 2018-01-08 14:02:03

乍一看还不错,但它把日子错当成了几个月。 所以我的问题是如何告诉python天就是天,月就是月?你知道吗

我希望你们中的一些人能帮助我


Tags: to数据代码dfdatetimedate时间pd
2条回答

使用此选项:

import pandas as pd

df["Date"]=pd.to_datetime(df["Date"], format='%d-%m-%Y %H:%M:%S')#you will specify in the format key what each number means so it doesn't misunderstands it

使用dayfirst=True

例如:

import pandas as pd
print(pd.to_datetime("01-08-2018 14:02:03", dayfirst=True))

输出:

2018-08-01 14:02:03

相关问题 更多 >