我怎样才能使python numpy的日期时间范围 [英] How can I make a python numpy arange of datetime

查看:300
本文介绍了我怎样才能使python numpy的日期时间范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些输入数据,输入文件中的时间戳以从文件名中指定的日期时间开始的小时数形式出现.

I have some input data, with timestamps in the input file in the form of hours from the date time specified in the filename.

这有点没用,所以我需要将其转换为python datetime.datetime对象,然后将其放入numpy数组中.我可以编写一个for循环,但是我想做些类似的事情:

This is a bit useless, so I need to convert it to python datetime.datetime objects, and then put it in a numpy array. I could write a for loop, but I'd like to do something like:

numpy.arange(datetime.datetime(2000, 1,1), datetime.datetime(2000, 1,2), datetime.timedelta(hours=1))

会引发TypeError.

which throws a TypeError.

可以做到吗?我被python 2.6和numpy 1.6.1困住了.

Can this be done? I'm stuck with python 2.6 and numpy 1.6.1.

推荐答案

请参见 NumPy日期时间和Timedeltas .基本上,您可以使用numpy.datetime64类型表示NumPy中的日期时间,这允许您执行值的范围.

See NumPy Datetimes and Timedeltas. Basically, you can represent datetimes in NumPy using the numpy.datetime64 type, which permits you to do ranges of values.

对于NumPy 1.6,它使用的datetime64类型要少得多,您可以使用适当的列表推导来构建日期时间(另请参见

For NumPy 1.6, which has a much less useful datetime64 type, you can use a suitable list comprehension to build the datetimes (see also Creating a range of dates in Python):

base = datetime.datetime(2000, 1, 1)
arr = numpy.array([base + datetime.timedelta(hours=i) for i in xrange(24)])

这产生

array([2000-01-01 00:00:00, 2000-01-01 01:00:00, 2000-01-01 02:00:00,
   2000-01-01 03:00:00, 2000-01-01 04:00:00, 2000-01-01 05:00:00,
   2000-01-01 06:00:00, 2000-01-01 07:00:00, 2000-01-01 08:00:00,
   2000-01-01 09:00:00, 2000-01-01 10:00:00, 2000-01-01 11:00:00,
   2000-01-01 12:00:00, 2000-01-01 13:00:00, 2000-01-01 14:00:00,
   2000-01-01 15:00:00, 2000-01-01 16:00:00, 2000-01-01 17:00:00,
   2000-01-01 18:00:00, 2000-01-01 19:00:00, 2000-01-01 20:00:00,
   2000-01-01 21:00:00, 2000-01-01 22:00:00, 2000-01-01 23:00:00], dtype=object)

这篇关于我怎样才能使python numpy的日期时间范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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