Given two datetimes (start_date
and end_date
), I'd like to generate a list of other datetimes between these two dates, the new datetimes being separated by a variable interval. e.g. every 4 days between 2011-10-10 and 2011-12-12 or every 8 hours between now and tomorrow 19p.m.
Maybe something roughly equivalent to the Dateperiod PHP class.
What would be the most efficient way to accomplish this in Python?
Try this:
The example in the question, "every 8 hours between now and tomorrow 19:00" would be written like this:
Notice that the valid values for
period
are those defined for therelativedelta
relative information, namely:'years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds', 'microseconds'
.My solution returns a list, as required in the question. If you don't need all the elements at once you can use generators, as in @MartijnPieters answer.
I really liked both answers by @Martijn Pieters and @Óscar López. Let me suggest my combined solution between those two answers.
Use
datetime.timedelta
:Works for both dates and datetime objects. Your second example:
The solutions suggested here work well for intervals of days, hours, etc. using
timedelta
, or anything thatdateutil.relativedelta
supports if you want to rely on third-party libraries. But I wanted to share my solution for the specific case of monthly intervals in the format yyyymm, asked here (but marked as a duplicate of this question).Output:
This solution is fairly specific to this particular need for yyyymm formatting (though it comes up frequently in my world, at least) and may not be the most efficient answer with the large number of
continue
s, but has the advantages of being concise, easy to understand, and doesn't involve a number of libraries or date-conversion code.