[英]Converting different date formats to a single format in a dataframe column
I want to make different date formats the same in my dataframe column.我想在我的数据框列中使不同的日期格式相同。
input:输入:
0 16.09.2014
1 2014-09-16
2 02.12.2014
3 2014-12-02
4 09.01.2018
183 2015-03-30
184 12.04.2017
185 2017-04-12
186 28.12.2018
187 2018-12-28
Name: invoiceDate, Length: 188, dtype: object
but I use:但我使用:
df['invoiceDate'] = pd.to_datetime(df['invoiceDate'], errors='coerce')
df['invoiceDate'].dt.strftime('%d.%m.%Y')
output: (it writes the first two in the same format but then it goes wrong and gets month by day and month by month.)输出:(它以相同的格式写入前两个,但随后出错并逐月逐月获取。)
0 16.09.2014
1 16.09.2014
2 12.02.2014 (true)
3 02.12.2014 (false)
4 01.09.2018
183 30.03.2015
184 04.12.2017 (true)
185 12.04.2017 (false)
186 28.12.2018
187 28.12.2018
Name: invoiceDate, Length: 188, dtype: object
If the output should be;如果输出应该是;
output :输出 :
0 16.09.2014
1 16.09.2014
2 02.12.2014
3 02.12.2014
4 09.01.2018
183 30.03.2015
184 12.04.2017
185 12.04.2017
186 28.12.2018
187 28.12.2018
Name: invoiceDate, Length: 188, dtype: object
In this particular case, you just need to pass dayfirst=True
to parse the dates as you intend在这种特殊情况下,您只需要传递
dayfirst=True
即可按照您的意图解析日期
df['invoiceDate'] = (
pd.to_datetime(df['invoiceDate'], errors='coerce', dayfirst=True)
.dt.strftime('%d.%m.%Y')
)
If you set the column of the dates to = date you could do the following如果您将日期列设置为 = date,您可以执行以下操作
df['Date'] = pd.to_datetime(df['Date'], infer_datetime_format=True)
from here you can simply tell it the format you want the date to be structured using a strftime从这里您可以简单地告诉它您希望使用 strftime 构造日期的格式
df['Date'] = df['Date'].apply(lambda x : x.strftime('%d.%m.%Y'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.