datetime - Python: Adding hour vector to date vector elementwise -


i have array of dates as:

>>> dates array([datetime.datetime(2013, 1, 1, 0, 0),        datetime.datetime(2013, 1, 2, 0, 0),        datetime.datetime(2013, 2, 1, 0, 0))], dtype=object) 

i have corresponding array of hours of same size dates:

numpy.asarray([3,5,2]) 

i want generate following:

>>> datesplushour array([datetime.datetime(2013, 1, 1, 3, 0),        datetime.datetime(2013, 1, 2, 5, 0),        datetime.datetime(2013, 2, 1, 2, 0))], dtype=object) 

i.e. add hour vector date vector element wise. hoping use better loop.

all need creating timedeltas hours numpy array tehm add dates:

>>> import datetime >>> import numpy np >>> dates = np.array([datetime.datetime(2013, 1, 1, 0, 0), ...        datetime.datetime(2013, 1, 2, 0, 0), ...        datetime.datetime(2013, 2, 1, 0, 0)], dtype=object) >>> >>> h = np.asarray([3,5,2]) >>> hours = np.array([datetime.timedelta(hours=i) in h]) >>> >>> dates + hours array([datetime.datetime(2013, 1, 1, 3, 0),        datetime.datetime(2013, 1, 2, 5, 0),        datetime.datetime(2013, 2, 1, 2, 0)], dtype=object) 

or more numpythonic approach can use np.vectorize in order apply function array's items instead of using list comprehension.

>>> f = np.vectorize(lambda x: datetime.timedelta(hours=x)) >>> f(h) + dates array([datetime.datetime(2013, 1, 1, 3, 0),        datetime.datetime(2013, 1, 2, 5, 0),        datetime.datetime(2013, 2, 1, 2, 0)], dtype=object) 

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -