In Python3, I can loop over a range of dates like this
import datetime
dt0 = datetime.datetime(2017, 1, 1, 0, 0, 0)
dt1 = datetime.datetime(2017, 1, 5, 0, 0, 0)
dt = dt0
while dt <= dt1:
print(dt.strftime("%Y-%m-%d %H:%M:%S"))
dt += datetime.timedelta(days=1)
Is there a similar way to loop over dates in Rust? I know that I could write a nested loop over the months then the days of the month. Like this:
let days = [1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21,
22, 23, 24, 25, 26, 27, 28, 29, 30, 31];
let months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
let months_30_days = [4, 6, 9, 11];
for month in months.iter() {
for day in days.iter() {
if month == &2 {
if is_leap_year(year) {
if day > &29 {
continue;
}
} else if day > &28 {
continue;
}
} else if months_30_days.contains(&month) && day > &30 {
continue;
}
print!("{:04}-{:02}-{:02} ", year, month, day);
}
}
fn is_leap_year(year: i32) -> bool {
if year % 100 == 0 {
return year % 400 == 0;
} else {
return year % 4 == 0;
}
}
Is there a more Rustic way to do it?
You could use the
chrono
crate for that:This can also be wrapped into an iterator:
There might be a crate that already provides such a functionality, but if you would like to implement this on your own, you could introduce a new data type and implement
Iterator
- that would be the Rust-y way to do it.Then you would be able to increment it in a loop using
next()
.