【问题标题】:Dealing with different date formats python?处理不同的日期格式python?
【发布时间】:2026-01-30 18:20:07
【问题描述】:

我正在使用pd.to_datetime(df['Date'], format="%d/%m/%Y") 方法尝试将该列转换为日期时间列。

现在,日期的格式为日/月/年,但格式不同,例如:

5/8/2005
13/08/05
4/2/2006

当我尝试使用 pd.to_datetime() 时出现错误:time data '13/08/05' does not match format '%d/%m/%Y' (match),当我删除格式时,pandas 会错误地转换日期。

我该如何处理?

【问题讨论】:

    标签: python python-3.x pandas date


    【解决方案1】:

    pd.to_datetime 中使用dayfirst 关键字:

    >>> pd.to_datetime(df['Date'], dayfirst=True)
    0   2005-08-05
    1   2005-08-13
    2   2006-02-04
    dtype: datetime64[ns]
    

    【讨论】:

      【解决方案2】:

      试试这个

      pd.to_datetime(df['Date'], dayfirst=True)
      

      【讨论】:

        【解决方案3】:

        我曾经遇到过类似的问题,在某些情况下,“Month First”“Day First”结合使用。我使用以下代码解决了这个问题。

        df=pd.DataFrame({"A":["5/8/2005","13/08/05","4/2/2006"]})
        df.loc[:,"IsMonth"]=df.loc[:,"A"].apply(lambda x: int(x.split("/")[0])>12)
        df_1=df[df.loc[:,"IsMonth"]==True]
        df_2=df[~df.index.isin(df_1.index)]
        
        df_1["A"]=pd.to_datetime(df_1["A"])
        df_2["A"]=pd.to_datetime(df_2["A"])
        
        df=pd.concat([df_1,df_2])
        df.drop("IsMonth", inplace=True, axis=1)
        

        请注意pd.to_datetime()的默认行为是使用dayfirst=False

        【讨论】:

          【解决方案4】:

          你不能直接处理它。您可以看到details on datetime formatting 并注意到有一个%y%Y 指令,分别表示2 位数和4 位数年份。(我不知道dayfirst,但我认为apply 用例对其他人仍然有帮助。)

          我建议创建一个小函数,然后在应用列上使用该函数。像这样的:

          >>> def convertYear(val):
          ...     (day, month, year) = val.split('/')
          ...     if len(year) == 2:
          ...         if int(year) > 40:
          ...             year = '19' + year
          ...         else:
          ...             year = '20' + year
          ...         newvals = [day, month, year]
          ...         return '/'.join(newvals)
          ...     return val
          

          那你可以call this function on the column of interest;类似:

          df.Date.apply(convertYear, axis='index') # don't use axis=0, not readability-friendly
          

          现在你终于可以完成了:

          pd.to_datetime(df['Date'], format="%d/%m/%Y"
          

          这里有龙

          请注意:尽管我的函数试图变得聪明,它假设你有欧洲日期(DD/MM/YYYY),我假设这是因为13/08/05。在美国,它是 (MM/DD/YYYY)。

          因为这个烦恼,正确的datetimes should be internationalized,这真的只是东亚风格。 (也许整个亚洲??)

          【讨论】: