我可以解析不同格式的日期吗? [英] Can I parse dates in different formats?

查看:54
本文介绍了我可以解析不同格式的日期吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个合作者数据中的日期格式不一致.

A collaborator of mine has inconsistent date formatting in their data.

0   13/11/2016
1   21/01/2017
2   22/01/2017
3   2017-02-02
4   2016-12-11
5   13/11/2016
6   2016-12-12
7   21/01/2017
8   22/01/2017
9   2017-02-02

我希望能够将其解析为时间戳,以便在 Python 中进行分析.使用 parse_dates = True 不起作用,我怀疑这是因为格式混合.

I'd like to be able to parse this into a timestamp for analysis in python. Using parse_dates = True doesn't work, and I suspect it is because of the mixture of formats.

我可以解析不同格式的日期吗?

Can I parse dates in different formats?

推荐答案

您可以使用 to_datetime:

You can use to_datetime:

第一种格式(YYYY-MM-DD):

print (df)
        dates
0  13/11/2016
1  21/01/2017
2  22/01/2017
3  2017-02-02
4  2016-12-11
5  13/11/2016
6  2016-12-12
7  21/01/2017
8  22/01/2017
9  2017-02-02
9  2017-02-25 <- YYYY-MM-DD

dates = pd.to_datetime(df.dates)
print (dates)
0   2016-11-13
1   2017-01-21
2   2017-01-22
3   2017-02-02
4   2016-12-11
5   2016-11-13
6   2016-12-12
7   2017-01-21
8   2017-01-22
9   2017-02-02
9   2017-02-25
Name: dates, dtype: datetime64[ns]

第二种格式(YYYY-DD-MM)

有点问题 - 在 to_datetime,最后 combine_firstfillna:

It is a bit problematic - need parameter format and errors='coerce' in to_datetime, last combine_first or fillna:

print (df)
        dates
0  13/11/2016
1  21/01/2017
2  22/01/2017
3  2017-02-02
4  2016-12-11
5  13/11/2016
6  2016-12-12
7  21/01/2017
8  22/01/2017
9  2017-02-02
9  2017-25-02 <- YYYY-DD-MM

dates1 = pd.to_datetime(df.dates, format='%d/%m/%Y', errors='coerce')
dates2 = pd.to_datetime(df.dates, format='%Y-%d-%m', errors='coerce')

dates = dates1.combine_first(dates2)
#dates = dates1.fillna(dates2)
print (dates)
0   2016-11-13
1   2017-01-21
2   2017-01-22
3   2017-02-02
4   2016-11-12
5   2016-11-13
6   2016-12-12
7   2017-01-21
8   2017-01-22
9   2017-02-02
9   2017-02-25
Name: dates, dtype: datetime64[ns]

这篇关于我可以解析不同格式的日期吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆