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 timedelta
s 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
Post a Comment