【问题标题】:Regular Expression for date in python? [duplicate]python中日期的正则表达式? [复制]
【发布时间】:2020-04-14 20:16:13
【问题描述】:

如何通过正则表达式检查 pandas 数据框中的日期值并选择错误的日期类型值?

日期:df

Date_col
22-01-2016
2016-01-22
2016/01/22
2018-12-25 09:27:53
22-Jan-2016
abcd
1203
2072006
20030201

输出:

Bad_Date
22-Jan-2016
abcd
1203
2072006
20030201

可能是只允许数字的正则表达式,'-' ,'/', ':' 可以解决这个问题。

【问题讨论】:

  • 您是要验证列是否只是具有特定的类似日期的格式,还是要验证正确的日期?
  • 例如,2019-02-30 是不是一个糟糕的约会? 2018-45-12呢?
  • 你会考虑闰年吗?
  • 你在乎10548年吗?比如10548-01-01?
  • 它应该包含正确的日期格式 22-07-2019 或 2019-07-22 否则它将是一个错误的日期。

标签: python regex python-3.x pandas python-2.7


【解决方案1】:

一个想法可能是查看 pandas.to_datetime 拒绝哪些值:

import pandas as pd

bad_times = []
for i in df.Date_col.values:
    try:
        pd.to_datetime(i)
    except ValueError:
        bad_times.append(i)

【讨论】:

    【解决方案2】:

    str.containsregular expressions 一起使用:

    wrong_dates1 = ~df['Date_col'].str.contains('[-/:]')   # rows without the characters -, /, :
    wrong_dates2 = df['Date_col'].str.contains('[A-Za-z]') # rows with letters
    
    df[wrong_dates1 | wrong_dates2]
    
          Date_col
    4  22-Jan-2016
    5         abcd
    6         1203
    7      2072006
    8     20030201
    

    旁注

    如果您将22-Jan-201620030201 视为有效日期(它们是),您可以简单地将pd.to_datetimeerrors='coerce' 一起使用,这会将无效日期转换为NaT

    bad_dates = pd.to_datetime(df['Date_col'], errors='coerce').isna()
    df[bad_dates]
    
      Date_col
    5     abcd
    6     1203
    7  2072006
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-20
      • 1970-01-01
      • 1970-01-01
      • 2018-09-18
      • 2011-06-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多