Python:将字符串中的多个日期格式更改为日期时间格式

cha*_*ons 2 python datetime date pandas

我正在尝试将字符串格式的不同日期转换为日期时间格式。我在“status_change_date”列中有大约 1,000,000 行日期。问题是有许多不同的格式,我不知道它们都是什么格式。

所以,我正在我的 jupyter 笔记上尝试这个功能:

def parsing_date(date_string):
    for date_format in ("%d/%m/%Y %H:%M:%S", "%m/%d/%Y %H:%M:%S", "%m/%d/%Y %H:%M:%S%p", "%d/%m/%Y %H:%M:%S%p", "%-m/%-d/%Y %H:%M:%S", "%-d/%-m/%Y %H:%M:%S", "%-m/%-d/%Y %H:%M:%S%p", "%-d/%-m/%Y %H:%M:%S%p"):
        try:
            return datetime.strptime(date_string, date_format)
        except ValueError:
            raise
            print(date_string)
        raise ValueError('Something is wrong')
Run Code Online (Sandbox Code Playgroud)

然后,

data['status_chage_date'].apply(parsing_date)
Run Code Online (Sandbox Code Playgroud)

我正在打印错误,以便我可以在我的函数中一一考虑,直到不再有错误为止。但是,我遇到此错误消息:

ValueError: time data '17/10/2019 05:49:51' does not match format '%m/%d/%Y %H:%M:%S'
Run Code Online (Sandbox Code Playgroud)

或者

strptime() argument 1 must be str, not None
Run Code Online (Sandbox Code Playgroud)

我以为我在函数中覆盖了格式,第二个错误很奇怪,因为我排除了具有 None 值的行。

我做错了什么,有没有更好的方法来做到这一点?

bco*_*a12 5

请注意,您在发生错误时引发!您需要先测试所有的可能性:

import pandas as pd 

def parsing_date(date_string):
    d = None
    for date_format in ("%d/%m/%Y %H:%M:%S", "%m/%d/%Y %H:%M:%S", "%m/%d/%Y %H:%M:%S%p", "%d/%m/%Y %H:%M:%S%p", "%-m/%-d/%Y %H:%M:%S", "%-d/%-m/%Y %H:%M:%S", "%-m/%-d/%Y %H:%M:%S%p", "%-d/%-m/%Y %H:%M:%S%p"):
        try:
            d = datetime.strptime(date_string, date_format)
            break
        except:
            pass
    if d is not None:
        return d
    else:
        return pd.NaT
Run Code Online (Sandbox Code Playgroud)

另请注意,如果您的日期和月份都在数字 1 到 12 之间,您将无法确定解析为正确的日期时间。如果可能,您应该寻找导致不同格式的原因并单独解析它们。