1

import timedelta as td I have a date time and I want to add an array of hours to it.

i.e.

Date[0]
datetime.datetime(2011, 1, 1, 0, 0)

Date[0] + td(hours=9)
datetime.datetime(2011, 1, 1, 9, 0)

hrs = [1,2,3,4]
Date[0] + td(hours=hrs)

But obviously it is not supported.

Date array above is a giant array of size 100X1 and I want to add hrs = [1,2,3,4] to each row of Date to get a datetime array of size 100x4. So, a for loop is not going to work in my case.

1
  • 1
    why isn't a for loop going to work?.. Commented Sep 26, 2016 at 20:02

1 Answer 1

2

Use a nested list comprehension and .replace() method. Sample for a list with 2 datetimes:

In [1]: from datetime import datetime

In [2]: l = [datetime(2011, 1, 1, 0, 0), datetime(2012, 1, 1, 0, 0)]

In [3]: hours = [1, 2, 3, 4]

In [4]: [[item.replace(hour=hour) for hour in hours] for item in l]
Out[4]: 
[[datetime.datetime(2011, 1, 1, 1, 0),
  datetime.datetime(2011, 1, 1, 2, 0),
  datetime.datetime(2011, 1, 1, 3, 0),
  datetime.datetime(2011, 1, 1, 4, 0)],
 [datetime.datetime(2012, 1, 1, 1, 0),
  datetime.datetime(2012, 1, 1, 2, 0),
  datetime.datetime(2012, 1, 1, 3, 0),
  datetime.datetime(2012, 1, 1, 4, 0)]]

As a result a 2x4 list of lists.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.