【问题标题】:Convert string to date in python if date string has different format如果日期字符串具有不同的格式,则在 python 中将字符串转换为日期
【发布时间】:2019-06-28 09:40:09
【问题描述】:

我的数据有两种不同日期格式的日期变量

Date
01 Jan 2019
02 Feb 2019
01-12-2019
23-01-2019
11-04-2019
22-05-2019

我想把这个字符串转换成日期(YYYY-mm-dd)

Date
2019-01-01
2019-02-01
2019-12-01
2019-01-23
2019-04-11
2019-05-22

我已经尝试过以下事情,但我正在寻找更好的方法

df['Date'] = np.where(df['Date'].str.contains('-'), pd.to_datetime(df['Date'], format='%d-%m-%Y'), pd.to_datetime(df['Date'], format='%d %b %Y'))

适合我的解决方案

df['Date_1']= np.where(df['Date'].str.contains('-'),df['Date'],np.nan)
df['Date_2']= np.where(df['Date'].str.contains('-'),np.nan,df['Date'])
df['Date_new'] = np.where(df['Date'].str.contains('-'),pd.to_datetime(df['Date_1'], format = '%d-%m-%Y'),pd.to_datetime(df['Date_2'], format = '%d %b %Y'))

【问题讨论】:

  • pd.to_datetime(df2['Date']) 工作...
  • 它为 '11-04-2019' 提供了不正确的输出
  • @Sangram 这是因为它假定日期尽可能在美国 foemat 中。查找文档,我相信 to_datetime 有一个参数可以先强制日期

标签: python pandas numpy datetime string-to-datetime


【解决方案1】:

只需使用选项dayfirst=True

pd.to_datetime(df.Date, dayfirst=True)

Out[353]:
0   2019-01-01
1   2019-02-02
2   2019-12-01
3   2019-01-23
4   2019-04-11
5   2019-05-22
Name: Date, dtype: datetime64[ns]

【讨论】:

    【解决方案2】:

    我的建议: 定义一个转换函数如下:

    import datetime as dt
    
    def conv_date(x):
        try:
            res = pd.to_datetime(dt.datetime.strptime(x, "%d %b %Y"))
        except ValueError:
            res = pd.to_datetime(dt.datetime.strptime(x, "%d-%m-%Y"))
        return res
    

    现在获取新的日期列如下:

    df['Date_new'] = df['Date'].apply(lambda x: conv_date(x))
    

    【讨论】:

      【解决方案3】:

      您可以借助 pandas 的 apply AND to_datetime 方法获得您想要的结果,如下所示:-

      import pandas pd
      
      def change(value):
          return pd.to_datetime(value)
      
      df = pd.DataFrame(data = {'date':['01 jan 2019']})
      
      df['date'] = df['date'].apply(change)
      df
      

      希望对你有帮助。

      【讨论】:

      • 第四次观察会失败。它将给出 2019 年 11 月 4 日而不是 2019 年 4 月 11 日
      • @Sangram pd.to_datetimeDD:MM:YY 的格式接受输入,据此转换值。如果这是您的4th Nov 2019,那么您必须输入日期为04-11-2019
      • 我可以理解,但我无法手动更改,因为我正在获取 dd-mm-YYYY 格式或我提到的其他格式的数据。
      【解决方案4】:

      这就像预期的那样工作 -

      import pandas as pd
      
      a = pd. DataFrame({
              'Date' : ['01 Jan 2019',
                      '02 Feb 2019',
                      '01-12-2019',
                      '23-01-2019',
                      '11-04-2019',
                      '22-05-2019']
          })
      a['Date'] = a['Date'].apply(lambda date: pd.to_datetime(date, dayfirst=True))
      
      print(a)
      

      【讨论】:

      • 第四次观察是 2019 年 11 月 4 日,应该是 2019 年 4 月 11 日
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-28
      • 2023-02-04
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      相关资源
      最近更新 更多