chrism
chrism

Reputation: 2933

Python get whole hour values between 2 datetime objects

I have 2 datetime values: 'start' and end'. I'd like to return a list of all the datetimes that fall exactly on the hour between the two (inclusive).

For example 'start' is 09:30 and 'end' is 14:00 (same day). The values I'd like returned are 10:00, 11:00, 12:00, 13:00, 14:00.

I guess what you would do is get the next whole hour after 'start', add it to a blank list, then create a loop that adds and hours, tests if it's less than (or equal to) 'end' and append it to the list if true.

What I can't figure out is how to get the nearest whole hour to the start datetime.

Upvotes: 1

Views: 2512

Answers (2)

Abdul Kader
Abdul Kader

Reputation: 5842

The best way to do that is using timedelta.

>>> from datetime import datetime, timedelta
>>> start = datetime.now()
>>> if start.minute >= 30:
...     start.replace(minute=0)+timedelta(hours=1)
... else:
...     start.replace(minute=0)

Upvotes: 1

John La Rooy
John La Rooy

Reputation: 304443

The easiest would be to replace the minutes and seconds of the start time with zero and then add one hour.

You will need a special case if the start time is exactly on the hour and you wish to include it

eg

>>> from datetime import datetime, timedelta
>>> start_time = datetime.now()
>>> start_time
datetime.datetime(2011, 5, 18, 20, 38, 55, 546000)
>>> first = start_time.replace(minute=0, second=0, microsecond=0)+timedelta(hours=1)
>>> first
datetime.datetime(2011, 5, 18, 21, 0)
>>> 

Upvotes: 3

Related Questions