将datetime字符串转换为datetime(python) [英] Converting datetime string to datetime in numpy (python)

查看:852
本文介绍了将datetime字符串转换为datetime(python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想转换

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

进入 Numpy datetime对象。

  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]]

raise ValueError:无法将对象转换为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]] 

如何将我的数组转换为符合 Numpy datetime64 函数要求?



我正在使用Numpy版本1.7.0。在python 3.4

解决方案

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


ISO 8601日期或日期时间格式的字符串


c code code code code code code code code code code code code $ code> 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)


I would like to convert

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

into a Numpy datetime object.

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"]] 

raised ValueError: Could not convert object to NumPy datetime. However, the following works as I intended

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

How can I convert my array into a format that conforms with Numpy's datetime64 function requirement?

I am using Numpy version 1.7.0. in python 3.4

解决方案

So far as I can tell, np.datetime64 only works with

strings in ISO 8601 date or datetime format

The to_datetime function in pandas seems to be more flexible:

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"])

Of course you can easily convert back to numpy:

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

这篇关于将datetime字符串转换为datetime(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆