【问题标题】:Converting datetime string to datetime in numpy (python)在numpy(python)中将日期时间字符串转换为日期时间
【发布时间】:2015-01-22 01:25:32
【问题描述】:

我想转换

['17-10-2010 07:15:30', '13-05-2011 08:20:35', "15-01-2013 09:09:09"]

Numpy 日期时间对象。

import numpy as np
[np.datetime64(x) for x in ['17-10-2010 07:15:30', '13-05-2011 08:20:35', "15-01-2013 09:09:09"]] 

提出ValueError: Could not convert object to NumPy datetime。但是,以下工作符合我的预期

[np.datetime64(x) for x in ['2010-10-17 07:15:30', '2011-05-13 08:20:35', "2012-01-15 09:09:09"]] 

如何将我的数组转换为符合Numpydatetime64 功能要求的格式?

我使用的是 Numpy 1.7.0 版。在 python 3.4 中

【问题讨论】:

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


    【解决方案1】:

    据我所知,np.datetime64 仅适用于

    strings in ISO 8601 date or datetime format

    pandas 中的to_datetime 函数似乎更灵活:

    import pandas as pd
    a=pd.to_datetime(['17-10-2010 07:15:30', '13-05-2011 08:20:35', "15-01-2013 09:09:09"])
    

    当然你可以轻松转换回numpy:

    np.array(a,dtype=np.datetime64)
    

    【讨论】:

    • np.array(a,dtype=np.datetime64) 很好,但它返回 '17-10-2010T07:15:30',如何使它成为 '17-10-2010 07:15 :30' ?
    • "pandas 中的 to_datetime 函数似乎更灵活",但在这种情况下,请注意date/time nightmare in pandas
    【解决方案2】:

    np.datetime64 使用格式 yyyy-mm-dd hh:mm:ss

    如果您有 5-6 个元素的列表,您可以直接使用 np.datetime64 数据类型,只需更改 list 中的日期 format(yyyy-mm-dd hh:mm:ss)

    例如:

    dates=['17-10-2010 07:15:30', '13-05-2011 08:20:35', "15-01-2013 09:09:09"]
    #to
    dates=['2010-10-17 07:15:30', '2011-05-13 08:20:35', "2013-01-15 09:09:09"]
    #then create an array by
    np.array(dates,dtype=np.datetime64)
    

    注意: list 中包含 5-6 个元素并不是理想的情况(当涉及到实际数据时),因此您必须在 pandas 中使用 to_datetime() 方法,因为它更多灵活高效:

    除了@atomh33ls给出的答案:

    pandas中使用to_datetime()方法后 您可以使用values 属性或to_numpy() 方法轻松地将其转换回numpy

    a.values
    #OR
    a.to_numpy()
    

    【讨论】:

      猜你喜欢
      • 2015-03-24
      • 2015-09-17
      • 2012-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      相关资源
      最近更新 更多