We can get the dates between two dates with single method call using the dedicated datesUntil method of a LocalDate class. The datesUntill returns the sequentially ordered Stream of dates starting from the date object whose method is called to the date given as method argument.
You can use simple date arithmetic to find the number of days between two dates in Python. Define the 2 dates between which you want to find the difference in days. Then subtract these dates to get a timedelta object and examine the day's property of this object to get the required result.
$dates = getBetweenDates('2021-11-01', '2021-11-10'); print_r($dates);
I came up with this:
from datetime import date, timedelta
start_date = date(2008, 8, 15)
end_date = date(2008, 9, 15) # perhaps date.now()
delta = end_date - start_date # returns timedelta
for i in range(delta.days + 1):
day = start_date + timedelta(days=i)
print(day)
The output:
2008-08-15
2008-08-16
...
2008-09-13
2008-09-14
2008-09-15
Your question asks for dates in-between but I believe you meant including the start and end points, so they are included. To remove the end date, delete the "+ 1" at the end of the range function. To remove the start date, insert a 1 argument to the beginning of the range function.
Using a list comprehension:
from datetime import date, timedelta
d1 = date(2008,8,15)
d2 = date(2008,9,15)
# this will give you a list containing all of the dates
dd = [d1 + timedelta(days=x) for x in range((d2-d1).days + 1)]
for d in dd:
print d
# you can't join dates, so if you want to use join, you need to
# cast to a string in the list comprehension:
ddd = [str(d1 + timedelta(days=x)) for x in range((d2-d1).days + 1)]
# now you can join
print "\n".join(ddd)
Essentially the same as Gringo Suave's answer, but with a generator:
from datetime import datetime, timedelta
def datetime_range(start=None, end=None):
span = end - start
for i in xrange(span.days + 1):
yield start + timedelta(days=i)
Then you can use it as follows:
In: list(datetime_range(start=datetime(2014, 1, 1), end=datetime(2014, 1, 5)))
Out:
[datetime.datetime(2014, 1, 1, 0, 0),
datetime.datetime(2014, 1, 2, 0, 0),
datetime.datetime(2014, 1, 3, 0, 0),
datetime.datetime(2014, 1, 4, 0, 0),
datetime.datetime(2014, 1, 5, 0, 0)]
Or like this:
In []: for date in datetime_range(start=datetime(2014, 1, 1), end=datetime(2014, 1, 5)):
...: print date
...:
2014-01-01 00:00:00
2014-01-02 00:00:00
2014-01-03 00:00:00
2014-01-04 00:00:00
2014-01-05 00:00:00
import datetime
d1 = datetime.date(2008,8,15)
d2 = datetime.date(2008,9,15)
diff = d2 - d1
for i in range(diff.days + 1):
print (d1 + datetime.timedelta(i)).isoformat()
import datetime
begin = datetime.date(2008, 8, 15)
end = datetime.date(2008, 9, 15)
next_day = begin
while True:
if next_day > end:
break
print next_day
next_day += datetime.timedelta(days=1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With