【问题标题】:Python: Changing multiple dates format in string to datetime formatPython:将字符串中的多个日期格式更改为日期时间格式
【发布时间】:2020-06-27 22:46:19
【问题描述】:

我正在尝试将字符串格式的不同日期转换为日期时间格式。我在“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')

那么,

data['status_chage_date'].apply(parsing_date)

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

ValueError: time data '17/10/2019 05:49:51' does not match format '%m/%d/%Y %H:%M:%S'

或

strptime() argument 1 must be str, not None

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

我做错了什么,有更好的方法吗?

【问题讨论】:

    标签: python pandas date datetime


    【解决方案1】:

    注意,当错误发生时你会引发!您需要先测试所有可能性:

    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
    

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

    【讨论】:

    • 如何测试所有可能性?使用您的代码,我得到一组错误作为输出。
    • 在循环中,您尝试了所有可能性。成功时,代码运行断线。由于 d 不是 none,它将返回 d。如果你测试所有的可能性都没有成功,你会返回 pd.NaT (None for Datetime)
    猜你喜欢
    • 2022-07-04
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多