使用datetime64将字符串转换为np.array,而不使用Pandas [英] converting a string to np.array with datetime64, NOT using Pandas

查看:95
本文介绍了使用datetime64将字符串转换为np.array,而不使用Pandas的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种将YYYYmmdd格式的日期转换为dtype ='datetime64'的np.array的方法.日期存储在另一个np.array中,但带有dtype ='float64'.

I'm looking for a way to convert dates given in the format YYYYmmdd to an np.array with dtype='datetime64'. The dates are stored in another np.array but with dtype='float64'.

我正在寻找一种避免熊猫的方法来实现这一目标!

I am looking for a way to achieve this by avoiding Pandas!

我已经尝试过与此答案中建议的类似操作,但作者指出"[...]如果(日期格式)为ISO 8601,您可以使用numpy [...]直接对其进行解析.

I already tried something similar as suggested in this answer but the author states that "[...] if (the date format) was in ISO 8601 you could parse it directly using numpy, [...]".

由于我的日期格式为YYYYmmdd,即IS(?)ISO 8601,因此应该可以使用numpy直接解析它.但是我不知道我是python和一般编码方面的初学者.

As the date format in my case is YYYYmmdd which IS(?) ISO 8601 it should be somehow possible to parse it directly using numpy. But I don't know how as I am a total beginner in python and coding in general.

我真的想避免使用Pandas,因为当有一种方法可以通过使用已经使用的模块来完成任务时,我不想膨胀我的脚本.我还阅读了它会降低速度的方法,此处.

I really try to avoid Pandas because I don't want to bloat my script when there is a way to get the task done by using the modules I am already using. I also read it would decrease the speed here.

推荐答案

如果没有其他人提出更多内置的东西,那么这是一个行人方法:

If noone else comes up with something more builtin, here is a pedestrian method:

>>> dates
array([19700101., 19700102., 19700103., 19700104., 19700105., 19700106.,
       19700107., 19700108., 19700109., 19700110., 19700111., 19700112.,
       19700113., 19700114.])
>>> y, m, d = dates.astype(int) // np.c_[[10000, 100, 1]] % np.c_[[10000, 100, 100]]
>>> y.astype('U4').astype('M8') + (m-1).astype('m8[M]') + (d-1).astype('m8[D]')
array(['1970-01-01', '1970-01-02', '1970-01-03', '1970-01-04',
       '1970-01-05', '1970-01-06', '1970-01-07', '1970-01-08',
       '1970-01-09', '1970-01-10', '1970-01-11', '1970-01-12',
       '1970-01-13', '1970-01-14'], dtype='datetime64[D]')

这篇关于使用datetime64将字符串转换为np.array,而不使用Pandas的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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