【问题标题】:How to check if a column has a particular Date format or not using DATETIME in python?python - 如何检查列是否具有特定的日期格式或不使用python中的日期时间?
【发布时间】:2021-06-13 00:37:26
【问题描述】:

我是 python 新手。我有一个数据框,其中有一个日期列,它有不同的格式。我想检查它是否遵循特定的日期格式。我没有跟随我想放弃它。我尝试使用 try except 并遍历行。但我正在寻找一种更快的方法来检查列是否遵循特定的日期格式。 If it is not following then it has to drop. Is there any faster way to do it? Using DATE TIME library?

My code:
Date_format = %Y%m%d
df =
    Date       abc
0  2020-03-22  q
1  03-12-2020  w
2  55552020    e
3  25122020    r
4  12/25/2020  r
5  1212202033  y

Excepted out:
 Date       abc
0  2020-03-22  q

【问题讨论】:

    标签: python dataframe date datetime date-formatting


    【解决方案1】:

    你可以试试

    pd.to_datetime(df.Date, errors='coerce')
    0   2020-03-22
    1   2020-03-12
    2          NaT
    3          NaT
    4   2020-12-25
    5          NaT
    

    那么删除空值很容易

    编辑: 对于给定的格式,您仍然可以利用pd.to_datetime

    datetimes = pd.to_datetime(df.Date, format='%Y-%m-%d', errors='coerce')
    datetimes
    0   2020-03-22
    1          NaT
    2          NaT
    3          NaT
    4          NaT
    5          NaT
    
    
    df.loc[datetimes.notnull()]
    

    另请注意,我使用的是 %Y-%m-%d 格式,我认为这是您根据预期输出想要的格式(不是您提供的 Date_format 格式)

    【讨论】:

    • 谢谢,但我已经尝试过了。我不想更改格式,我只想检查它们是否处于特定模式。妈的!我忘了添加格式。请重新检查。我已经更新了
    • 非常感谢 :)
    猜你喜欢
    • 1970-01-01
    • 2023-03-27
    • 2020-03-08
    • 2019-11-21
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    • 2011-10-14
    • 1970-01-01
    相关资源
    最近更新 更多