【问题标题】:String to date time format in PandasPandas 中的字符串到日期时间格式
【发布时间】:2018-12-03 11:30:02
【问题描述】:

我有一个包含日期列的 csv 文件。日期的格式为“1stNov”、“22ndNov”等。如何以编程方式将它们转换为 Pandas 中的日期时间?

【问题讨论】:

  • 请出示您的资料
  • 那么最后三个字母是月份?
  • 试试:pd.read_csv(filepath, parse_dates = True)
  • 是的,过去三个月是几个月

标签: python python-3.x pandas csv datetime


【解决方案1】:

不是 Pandas 特有的问题,而是字符串/模式匹配的问题。使用Python's strftime directives。另请注意,您必须提供一年:datetime 内部对象必须持有一年。所以使用普通的 Python:

from datetime import datetime

L = ["1stNov", "22ndNov"]
res = [datetime.strptime(i[:-5] + i[-3:] + '2018', '%d%b%Y') for i in L]

[datetime.datetime(2018, 11, 1, 0, 0),
 datetime.datetime(2018, 11, 22, 0, 0)]

或者使用熊猫:

s = pd.Series(L)
res = pd.to_datetime(s.str[:-5] + s.str[-3:] + '2018', format='%d%b%Y')

0   2018-11-01
1   2018-11-22
dtype: datetime64[ns]

【讨论】:

    【解决方案2】:

    parser使用列表推导:

    df = pd.DataFrame({'dates':["1stNov", "22ndNov"]})
    
    from dateutil import parser
    df['dates'] = [parser.parse(f'{x[:-3]} {x[-3:]} 2018') for x in df['dates']]
    

    或者删除stnd字符串并转换to_datetime

    #python 3.6+ solution with f-strings
    dates = [(f'{x[:-5]}{x[-3:]}2018') for x in df['dates']]
    #python bellow 3.6
    #dates = ['{}{}2018'.format(x[:-5], x[-3:]) for x in df['dates']]
    df['dates'] = pd.to_datetime(dates, format='%d%b%Y')
    
    print (df)
           dates
    0 2018-11-01
    1 2018-11-22
    

    【讨论】:

      猜你喜欢
      • 2020-05-29
      • 1970-01-01
      • 1970-01-01
      • 2016-12-22
      • 2017-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-23
      相关资源
      最近更新 更多