如何从包含日期时间对象的数组中进行插值? [英] How do you interpolate from an array containing datetime objects?

查看:123
本文介绍了如何从包含日期时间对象的数组中进行插值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个类似于np.interp的功能,该功能可以与datetime对象一起使用.

I'm looking for a function analogous to np.interp that can work with datetime objects.

例如:

import datetime, numpy as np
arr1 = np.array([datetime.datetime(2008,1,d) for d in range(1,10)])
arr2 = np.arange(1,10)

np.interp(datetime.datetime(2008,1,5,12),arr1,arr2)

理想情况下会返回5.5,但是numpy会引发TypeError: array cannot be safely cast to required type.有解决这个问题的好方法吗?

would ideally return 5.5, but numpy raises TypeError: array cannot be safely cast to required type. Is there a nice pythonic way around this?

推荐答案

您可以将它们转换为时间戳(已编辑,以反映使用calendar.timegm以避免与时区相关的陷阱).

You can convert them to timestamps (edited to reflect the use of calendar.timegm to avoid timezone-related pitfalls).

# Python 2.7
import datetime, numpy as np
import calendar

def toTimestamp(d):
  return calendar.timegm(d.timetuple())

arr1 = np.array([toTimestamp(datetime.datetime(2008,1,d)) for d in range(1,10)]) 
arr2 = np.arange(1,10)

result = np.interp(toTimestamp(datetime.datetime(2008,1,5,12)),arr1,arr2)
print result # Prints 5.5

这篇关于如何从包含日期时间对象的数组中进行插值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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