在numpy(python)中将日期时间字符串转换为日期时间

Posted

技术标签:

【中文标题】在numpy(python)中将日期时间字符串转换为日期时间【英文标题】:Converting datetime string to datetime in 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 中

【问题讨论】:

【参考方案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()

【讨论】:

以上是关于在numpy(python)中将日期时间字符串转换为日期时间的主要内容,如果未能解决你的问题,请参考以下文章

如何在python中将字符串日期转换为日期时间格式? [复制]

如何在python中将字符串转换为日期时间[重复]

如何在 pandas python 中将字符串转换为日期时间格式?

仅在 Python 中将 datetime 对象转换为日期字符串

如何编写一个正则表达式命令在 python 中将字符串转换为日期时间格式?

在 Python 中将一列日期时间转换为纪元