How can i loop through a daterange with different intervals?
Loop until the from
date plus 1.day
, 1.week
, or 1.month
is greater than the to
date?
> from = Time.now
=> 2012-05-12 09:21:24 -0400
> to = Time.now + 1.month + 2.week + 3.day
=> 2012-06-29 09:21:34 -0400
> tmp = from
=> 2012-05-12 09:21:24 -0400
> begin
?> tmp += 1.week
?> puts tmp
?> end while tmp <= to
2012-05-19 09:21:24 -0400
2012-05-26 09:21:24 -0400
2012-06-02 09:21:24 -0400
2012-06-09 09:21:24 -0400
2012-06-16 09:21:24 -0400
2012-06-23 09:21:24 -0400
2012-06-30 09:21:24 -0400
=> nil
How do I loop through a date range?
Well, you'll need to loop over them one way or the other. I prefer defining a method like this:
public IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
{
for(var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1))
yield return day;
}
Then you can use it like this:
foreach (DateTime day in EachDay(StartDate, EndDate))
// print it or whatever
In this manner you could hit every other day, every third day, only weekdays, etc. For example, to return every third day starting with the "start" date, you could just call AddDays(3)
in the loop instead of AddDays(1)
.
Iterating through a range of dates in Python
Why are there two nested iterations? For me it produces the same list of data with only one iteration:
for single_date in (start_date + timedelta(n) for n in range(day_count)):
print ...
And no list gets stored, only one generator is iterated over. Also the "if" in the generator seems to be unnecessary.
After all, a linear sequence should only require one iterator, not two.
Update after discussion with John Machin:
Maybe the most elegant solution is using a generator function to completely hide/abstract the iteration over the range of dates:
from datetime import date, timedelta
def daterange(start_date, end_date):
for n in range(int((end_date - start_date).days)):
yield start_date + timedelta(n)
start_date = date(2013, 1, 1)
end_date = date(2015, 6, 2)
for single_date in daterange(start_date, end_date):
print(single_date.strftime("%Y-%m-%d"))
NB: For consistency with the built-in range()
function this iteration stops before reaching the end_date
. So for inclusive iteration use the next day, as you would with range()
.
loop through date intervals to create multiple variables
Here is a solution to create the matrix of years associated with the date range:
library(lubridate)
library(tidyr)
library(dplyr)
df <- data.frame(date1 = c("2011-09-18", "2013-03-06", "2013-08-08"),
date2 = c("2012-02-18", "2014-03-06", "2015-02-03"))
df$date1 <- as.Date(parse_date_time(df$date1, "ymd"))
df$date2 <- as.Date(parse_date_time(df$date2, "ymd"))
#identify the years associated with each row.
df$year<-sapply(1:nrow(df), function(i){
paste(seq(as.numeric(format(df$date1[i], "%Y")),
as.numeric(format(df$date2[i], "%Y"))), collapse = ",")})
#separate and convert to wide format
df %>% separate_rows( year, sep=",") %>%
mutate(value=1) %>%
spread(key=year, value=value, fill=0)
# date1 date2 2011 2012 2013 2014 2015
# 1 2011-09-18 2012-02-18 1 1 0 0 0
# 2 2013-03-06 2014-03-06 0 0 1 1 0
# 3 2013-08-08 2015-02-03 0 0 1 1 1
Using the between
function is a viable option to test if a particular date is within the range.
Loop through a date range with JavaScript
Here's a way to do it by making use of the way adding one day causes the date to roll over to the next month if necessary, and without messing around with milliseconds. Daylight savings aren't an issue either.
var now = new Date();
var daysOfYear = [];
for (var d = new Date(2012, 0, 1); d <= now; d.setDate(d.getDate() + 1)) {
daysOfYear.push(new Date(d));
}
Note that if you want to store the date, you'll need to make a new one (as above with new Date(d)
), or else you'll end up with every stored date being the final value of d
in the loop.
For loop through a specific time interval
Try this approach.
from datetime import datetime, timedelta
date_range = 3
for m,t in zip(my_emails, sent_date):
t = datetime.strptime(t, '%m/%d/%Y')
before_dates = [ t - timedelata(i) for i in range(1,date_range+1)]
after_dates = [ t + timedelata(i) for i in range(1,date_range+1)]
#do stuff with mail(m) and dates
What is the most effective way to iterate over a date range in Swift?
If I understand your question correctly, the user will check off some weekdays and provide a duration as a number of days.
Assuming you have the selected weekdays in an array and the duration, you can get the list of matching dates as follows:
// User selected weekdays (1 = Sunday, 7 = Saturday)
var selectedWeekdays = [2, 4, 6] // Example - Mon, Wed, Fri
var duration = 10 // Example - 10 days
let calendar = Calendar.current
var today = Date()
let dateEnding = calendar.date(byAdding: .day, value: duration, to: today)!
var matchingDates = [Date]()
// Finding matching dates at midnight - adjust as needed
let components = DateComponents(hour: 0, minute: 0, second: 0) // midnight
calendar.enumerateDates(startingAfter: today, matching: components, matchingPolicy: .nextTime) { (date, strict, stop) in
if let date = date {
if date <= dateEnding {
let weekDay = calendar.component(.weekday, from: date)
print(date, weekDay)
if selectedWeekdays.contains(weekDay) {
matchingDates.append(date)
}
} else {
stop = true
}
}
}
print("Matching dates = \(matchingDates)")
I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?
$begin = new DateTime('2010-05-01');
$end = new DateTime('2010-05-10');
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);
foreach ($period as $dt) {
echo $dt->format("l Y-m-d H:i:s\n");
}
This will output all days in the defined period between $start
and $end
. If you want to include the 10th, set $end
to 11th. You can adjust format to your liking. See the PHP Manual for DatePeriod. It requires PHP 5.3.
iterate through a list of dates and calculate number of days in between each interval
You can convert first to_datetime
and then subtract all values without first with all values without last:
dates = pd.to_datetime(dates, format='%d/%m/%Y')
delta = dates[:-1] - dates[1:]
print (delta)
TimedeltaIndex(['30 days', '28 days', '35 days', '27 days', '29 days',
'35 days', '27 days', '36 days', '27 days', '28 days',
'29 days', '35 days', '28 days', '28 days', '35 days',
'27 days', '35 days', '29 days', '28 days', '35 days',
'28 days', '28 days', '28 days', '35 days', '28 days',
'35 days', '28 days', '27 days', '35 days', '29 days',
'28 days', '35 days', '28 days', '35 days', '28 days',
'26 days'],
dtype='timedelta64[ns]', freq=None)
And if need integers add TimedeltaIndex.days
:
delta = (dates[:-1] - dates[1:]).days
print (delta)
Int64Index([30, 28, 35, 27, 29, 35, 27, 36, 27, 28, 29, 35, 28, 28, 35, 27, 35,
29, 28, 35, 28, 28, 28, 35, 28, 35, 28, 27, 35, 29, 28, 35, 28, 35,
28, 26],
dtype='int64')
delta = (dates[:-1] - dates[1:]).days.tolist()
print (delta)
[30, 28, 35, 27, 29, 35, 27, 36, 27, 28, 29, 35, 28, 28, 35, 27, 35, 29, 28,
35, 28, 28, 28, 35, 28, 35, 28, 27, 35, 29, 28, 35, 28, 35, 28, 26]
Related Topics
Rails - Displaying Foreign Key References in a Form
Model Using Modules in Rails Application
Cucumber + Webrat + Selenium Guide
Sinatra Static Assets Are Not Found When Using Rackup
How to Ignore Multiline Comments in SASS
Get Link and Href Text from HTML Doc with Nokogiri & Ruby
How to Use Basic Authentication with Httparty in a Rails App
Ruby: How to Group a Ruby Array
Rspec Stubbing Method for Only Specific Arguments
How to Access Firefox Extension I Added in Selenium Webdriver
How to Tokenize This String in Ruby
How to Prevent Pipe Character from Causing a Bad Uri Error in Rails 3/Ruby 1.9.2
Can't Enter Umlauts in Ruby 1.9.3 Irb