在numpy中将文本转换为datetime64

时间:2014-08-24 11:37:49

标签: python arrays date datetime numpy

我有numpy字符串数组(p.s.为什么字符串表示为对象?!)

t = array(['21/02/2014 08:40:00 AM', '11/02/2014 10:50:00 PM',
           '07/04/2014 05:50:00 PM', '17/02/2014 10:20:00 PM',
           '07/03/2014 06:10:00 AM', '02/03/2014 12:25:00 PM',
           '05/02/2014 03:20:00 AM', '31/01/2014 12:30:00 AM',
           '28/02/2014 01:25:00 PM'], dtype=object)

我想用日期分辨率将其转换为numpy.datetime64,但我找到的唯一解决方案是:

t = [datetime.strptime(tt,"%d/%m/%Y %H:%M:%S %p") for tt in t]
t = np.array(t,dtype='datetime64[us]').astype('datetime64[D]')

它可能比那更丑陋吗?为什么我需要浏览本机Python列表? 必须有另一种方式......

顺便说一句,我找不到在numpy / pandas中绘制日期直方图的方法

1 个答案:

答案 0 :(得分:0)

日期格式是问题,01/01/2015是不明确的,如果它在ISO 8601中你可以使用numpy直接解析它,在你的情况下因为你只想要日期然后拆分和重新排列数据将是显着的更快:

t = np.array([datetime.strptime(d.split(None)[0], "%d/%m/%Y") 
for d in t],dtype='datetime64[us]').astype('datetime64[D]')

一些时间,解析后首先重新排列:

In [36]: %%timeit
from datetime import datetime
t = np.array(['21/02/2014 08:40:00', '11/02/2014 10:50:00 PM',
           '07/04/2014 05:50:00 PM', '17/02/2014 10:20:00 PM',
           '07/03/2014 06:10:00 AM', '02/03/2014 12:25:00 PM',
           '05/02/2014 03:20:00 AM', '31/01/2014 12:30:00 AM',
           '28/02/2014 01:25:00 PM']*10000)
t1 = np.array([np.datetime64("{}-{}-{}".format(c[:4], b, a)) for a, b, c in (s.split("/", 2) for s in t)])
....: 
10 loops, best of 3: 125 ms per loop

您的代码:

In [37]: %%timeit
from datetime import datetime
t = np.array(['21/02/2014 08:40:00 AM', '11/02/2014 10:50:00 PM',
           '07/04/2014 05:50:00 PM', '17/02/2014 10:20:00 PM',
           '07/03/2014 06:10:00 AM', '02/03/2014 12:25:00 PM',
           '05/02/2014 03:20:00 AM', '31/01/2014 12:30:00 AM',
           '28/02/2014 01:25:00 PM']*10000)
t = [datetime.strptime(tt,"%d/%m/%Y %H:%M:%S %p") for tt in t]
t = np.array(t,dtype='datetime64[us]').astype('datetime64[D]')
....: 
1 loops, best of 3: 1.56 s per loop

两者给出相同结果的显着差异:

In [48]: t = np.array(['21/02/2014 08:40:00 AM', '11/02/2014 10:50:00 PM',
              '07/04/2014 05:50:00 PM', '17/02/2014 10:20:00 PM',
              '07/03/2014 06:10:00 AM', '02/03/2014 12:25:00 PM',
              '05/02/2014 03:20:00 AM', '31/01/2014 12:30:00 AM',
              '28/02/2014 01:25:00 PM'] * 10000)

In [49]: t1 = [datetime.strptime(tt,"%d/%m/%Y %H:%M:%S %p") for tt in t]
t1 = np.array(t1,dtype='datetime64[us]').astype('datetime64[D]')
   ....: 

In [50]: t2 = np.array([np.datetime64("{}-{}-{}".format(c[:4], b, a)) for a, b, c in (s.split("/", 2) for s in t)])

In [51]: (t1 == t2).all()
Out[51]: True