How do you interpolate from an array containing datetime objects?

后端 未结 4 1906
既然无缘
既然无缘 2020-12-31 09:44

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

For example:

import datetime, numpy         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-31 10:15

    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
    

提交回复
热议问题