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 returne开发者_如何学Cd 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.
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)
>>>
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)
精彩评论