【问题标题】:Swapping Str to Datetime in a CSV (Python)在 CSV (Python) 中将 Str 交换为日期时间
【发布时间】:2019-05-05 07:10:59
【问题描述】:

我有一个名为 aero 的数据集 我正在尝试将给定列中的字符串日期更改为日期时间 这是字符串的格式:

In: aero['Date Local'].unique()
Out: array(['2000-01-01', '2000-01-02', '2000-01-03', ..., '2016-03-04',
   '2016-03-05', '2016-03-06'], dtype=object)

如果我错了,请纠正我,但这看起来像是一个可变的字符串列表 这是我尝试过的代码:

for stuff in aero['Date Local']:
aero['Date Local'][stuff] = datetime.datetime.strptime(stuff, "%Y-%m-%d")  

产生了错误:

ValueError: ['2' '0' '0' '0' '-' '0' '1' '-' '0' '1'] not contained in the index

我试图弄清楚这意味着什么,但无济于事。有人可以帮我将这些字符串转换为日期时间吗?

【问题讨论】:

    标签: python string python-3.x numpy datetime


    【解决方案1】:

    您在循环的每次迭代中定义一个新变量stuff。那不是你想要的。您可以使用astype 将您的数组转换为datetime

    A = np.array(['2000-01-01', '2000-01-02', '2000-01-03', '2016-03-04',
                  '2016-03-05', '2016-03-06'], dtype=object)
    
    res = A.astype('datetime64[ns]')
    
    print(res)
    
    array(['2000-01-01T00:00:00.000000000', '2000-01-02T00:00:00.000000000',
           '2000-01-03T00:00:00.000000000', '2016-03-04T00:00:00.000000000',
           '2016-03-05T00:00:00.000000000', '2016-03-06T00:00:00.000000000'],
          dtype='datetime64[ns]')
    

    同样,如果你有 Pandas,你可以使用pd.to_datetime

    import pandas as pd
    
    res = pd.to_datetime(A).values  # .values extracts NumPy array
    

    因此,假设 aero 是 Pandas 数据框,您可以使用:

    aero['Date Local'] = pd.to_datetime(aero['Date Local'])
    

    【讨论】:

      猜你喜欢
      • 2017-01-30
      • 1970-01-01
      • 1970-01-01
      • 2010-12-28
      • 1970-01-01
      • 2018-11-21
      • 1970-01-01
      • 2018-06-23
      • 1970-01-01
      相关资源
      最近更新 更多