I need to start from, for example, January 1 2013, and "do some things" for each date, resulting in a JSON file for each date.
I have the "do some things" part worked out for a single date, but I'm having a hard time starting at a date and looping through to another end date.
to add a while loop that loops from the initial value of start_date to end_date by using the start_date <= end_date condition for the while loop. In the loop body, we print the current start_date and then add timedelta to start_date at the end of each iterator.
There are a few ways to do this, but I've gone with the following: last_date = datetime(year, month + 1, 1) + timedelta(days=-1) . This will calculate the first date of the following month, then subtract 1 day from it to get the last date of the current month.
You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes. Remember to increase the index by 1 after each iteration.
In this article, we will discuss how to iterate DateTime through a range of dates. Timedelta is used to get the dates and loop is to iterate the date from the start date to end date delta = datetime.timedelta (days=1) while (start_date <= end_date): print (start_date) start_date += delta
Calculate end date from start date and duration (years, months and days): To get end date based on given start date and number of years,months and days, please apply the below formula: Note: In this formula: A2 is the start date and B2 is the duration of year, C2 is the duration of month, and D2 is the duration of day that you want to add.
Java 9 introduces the method datesUntil, which lets us use the Stream API to iterate from start date to end date. Let's update our example code to take advantage of this feature:
The start_dateand end_datevariables are datetime.dateobjects because I don't need the timestamps. (They're going to be used to generate a report). Sample Output For a start date of 2009-05-30and an end date of 2009-06-09:
You can use ranges :
(Date.new(2012, 01, 01)..Date.new(2012, 01, 30)).each do |date| # Do stuff with date end
or (see @awendt answer)
Date.new(2012, 01, 01).upto(Date.new(2012, 01, 30)) do |date| # Do stuff with date end
You could use:
first.upto(last) do |date|
where first
and last
are Date objects.
See what I did here in a project of mine, for example.
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