如何将`numpy.datetime64`的列表转换为`matplotlib.dates`?

时间:2017-09-23 05:06:07

标签: python numpy matplotlib

这是我的简单对象:

[numpy.datetime64('2017-01-03T00:00:00.000000000'),
 numpy.datetime64('2017-01-04T00:00:00.000000000'),
 numpy.datetime64('2017-01-05T00:00:00.000000000'),
 numpy.datetime64('2017-01-06T00:00:00.000000000'),
 numpy.datetime64('2017-01-09T00:00:00.000000000'),
 numpy.datetime64('2017-01-10T00:00:00.000000000'),
 numpy.datetime64('2017-01-11T00:00:00.000000000'),
 numpy.datetime64('2017-01-12T00:00:00.000000000'),
 numpy.datetime64('2017-01-13T00:00:00.000000000'),
 numpy.datetime64('2017-01-16T00:00:00.000000000'),
 numpy.datetime64('2017-01-17T00:00:00.000000000'),
 numpy.datetime64('2017-01-18T00:00:00.000000000'),
 numpy.datetime64('2017-01-19T00:00:00.000000000'),
 numpy.datetime64('2017-01-20T00:00:00.000000000'),
 numpy.datetime64('2017-01-23T00:00:00.000000000'),
 numpy.datetime64('2017-01-24T00:00:00.000000000'),
 numpy.datetime64('2017-01-25T00:00:00.000000000'),
 numpy.datetime64('2017-01-26T00:00:00.000000000'),
 numpy.datetime64('2017-01-27T00:00:00.000000000'),
 numpy.datetime64('2017-02-01T00:00:00.000000000')]

而不是使用循环一个空列表逐个转换,是否有任何快捷方式?谢谢。

1 个答案:

答案 0 :(得分:2)

我最喜欢的解决方案是在这个帖子中看起来有点隐藏: Converting between datetime, Timestamp and datetime64,即使用tolist()。由于tolist()会返回不同的类型,因此根据数组类型,需要转换为ms来获取datetime个对象。可以使用matplotlib直接绘制datetime个对象,也可以在其上应用matplotlib.dates.date2num()

所以如果a是如上所述的numpy数组,那么

x = a.astype("M8[ms]").tolist()

会生成一个日期时间对象列表。

完整示例:

import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
import matplotlib.dates as mdates

a = np.array([np.datetime64('2017-01-03T00:00:00.000000000'),
     np.datetime64('2017-01-04T00:00:00.000000000'),
     np.datetime64('2017-01-05T00:00:00.000000000'),
     np.datetime64('2017-01-06T00:00:00.000000000'),
     np.datetime64('2017-01-09T00:00:00.000000000'),
     np.datetime64('2017-01-10T00:00:00.000000000'),
     np.datetime64('2017-01-11T00:00:00.000000000'),
     np.datetime64('2017-01-12T00:00:00.000000000'),
     np.datetime64('2017-01-13T00:00:00.000000000'),
     np.datetime64('2017-01-16T00:00:00.000000000'),
     np.datetime64('2017-01-17T00:00:00.000000000'),
     np.datetime64('2017-01-18T00:00:00.000000000'),
     np.datetime64('2017-01-19T00:00:00.000000000'),
     np.datetime64('2017-01-20T00:00:00.000000000'),
     np.datetime64('2017-01-23T00:00:00.000000000'),
     np.datetime64('2017-01-24T00:00:00.000000000'),
     np.datetime64('2017-01-25T00:00:00.000000000'),
     np.datetime64('2017-01-26T00:00:00.000000000'),
     np.datetime64('2017-01-27T00:00:00.000000000'),
     np.datetime64('2017-02-01T00:00:00.000000000')])

x = a.astype("M8[ms]").tolist()
y = np.random.rand(len(a))

plt.plot(x, y, color="limegreen")

plt.show()