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 a
Solution 1:
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)
>>>
Solution 2:
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)
Post a Comment for "Python Get Whole Hour Values Between 2 Datetime Objects"