使用 datetime64 将字符串转换为 np.array,而不是使用 Pandas

converting a string to np.array with datetime64, NOT using Pandas

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

我正在寻找一种方法来避免 Pandas!

我已经尝试过类似 answer 中建议的方法,但作者指出“[...] 如果(日期格式)采用 ISO 8601,您可以使用 numpy 直接解析它,[. ..]”。

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

我真的尽量避免 Pandas 因为我不想在有办法通过使用我已经在使用的模块来完成任务时使我的脚本膨胀。我还读到它会降低速度 here.

如果没有其他人想出更多内置的东西,这里是一个简单的方法:

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

您可以通过 python 日期时间模块。

from datetime import datetime
import numpy as np

datestrings = np.array(["18930201", "19840404"])
dtarray = np.array([datetime.strptime(d, "%Y%m%d") for d in datestrings], dtype="datetime64[D]")
print(dtarray)

# out: ['1893-02-01' '1984-04-04'] datetime64[D]

由于真正的问题 seems to be 如何将给定的字符串转换为 matplotlib 日期时间格式,

from datetime import datetime
import numpy as np
from matplotlib import dates as mdates

datestrings = np.array(["18930201", "19840404"])
mpldates = mdates.datestr2num(datestrings)
print(mpldates)

# out: [691071. 724370.]