python - 格式化与python真正不一致的日期

标签 python datetime pandas

我有一些非常困惑的日期,如果适用的话,我正试图将其转换为一致的格式 %Y-%m-%d。有些日期缺少日期,有些日期是 future 的日期,或者对于那些我将标记为不正确的日期来说根本不可能。我该如何解决与 Python 的这种不一致?

sample dates:
4-Jul-97
8/31/02
20-May-95
5/12/92
Jun-13
8/4/98
90/1/90
3/10/77
7-Dec
nan
4/3/98
Aug-76
Mar-90
Sep, 2020
Apr-74
10/10/03
Dec-00

最佳答案

如果需要,您可以使用 dateutil 解析器

from dateutil.parser import parse
bad_dates = [...]
for d in bad_dates:
    try:
        print parse(d)
    except Exception, err:
        print 'couldn\'t parse', d, err

输出

1997-07-04 00:00:00
2002-08-31 00:00:00
1995-05-20 00:00:00
1992-05-12 00:00:00
2015-06-13 00:00:00
1998-08-04 00:00:00
couldn't parse 90/1/90 day is out of range for month
1977-03-10 00:00:00
2015-12-07 00:00:00
couldn't parse nan unknown string format
1998-04-03 00:00:00
1976-08-30 00:00:00
1990-03-30 00:00:00
2020-09-30 00:00:00
1974-04-30 00:00:00
2003-10-10 00:00:00
couldn't parse Dec-00 day is out of range for month

如果您想标记任何不容易解析的内容,您可以检查它们是否有 3 个部分要解析,以及它们是否尝试解析它,或者像这样标记它

flagged, good = [],[]
splitters = ['-', ',', '/']
for d in bad_dates:
    try:
        a = None
        for s in splitters:
            if len(d.split(s)) == 3:
                a = parse(d)
                good.append(a)
        if not a:
            raise Exception
    except Exception, err:
        flagged.append(d)

关于python - 格式化与python真正不一致的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31152414/

相关文章:

python - 如何访问 pandas HDStore (pyTables) 中的索引

python - 如何使用 pandas 和每月 groupby 绘制时间序列?

python - Pandas :无法更改列数据类型

python - 根据列表从具有重复列的 DF 中选择行

python - Numpy:如何获得属性为真的最小索引

sql-server - 如何在 laravel 中格式化 sql server 的日期时间?

mysql - 错误 #1265 - 无法在默认 'none' 字段中插入空值

python - 从 python 脚本创建可执行文件

python - 使用 PythonTokenStream 的 PyLucene 自定义 TokenStream

c# - 准确的日期时间字符串格式