Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Vector of All Days Between Two Dates

Tags:

r

lubridate

Is there an easy way in R for me to itemize all valid days that occurred between two specified dates? For instance, I'd like the following inputs:

itemizeDates(startDate="12-30-11", endDate="1-4-12") 

To produce the following dates:

"12-30-11" "12-31-11", "1-1-12", "1-2-12", "1-3-12", "1-4-12" 

I'm flexible on classes and formatting of the dates, I just need an implementation of the concept.

like image 353
Jeff Allen Avatar asked Jan 22 '13 01:01

Jeff Allen


People also ask

How do I generate all dates between two dates?

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.

How do I get a list of days between two dates in Python?

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.

How do I get all dates between start and end date?

To get all of the dates between 2 dates: Copied! function getDatesInRange(startDate, endDate) { const date = new Date(startDate. getTime()); const dates = []; while (date <= endDate) { dates.


1 Answers

You're looking for seq

> seq(as.Date("2011-12-30"), as.Date("2012-01-04"), by="days") [1] "2011-12-30" "2011-12-31" "2012-01-01" "2012-01-02" "2012-01-03" [6] "2012-01-04" 

Or, you can use :

> as.Date(as.Date("2011-12-30"):as.Date("2012-01-04"), origin="1970-01-01") [1] "2011-12-30" "2011-12-31" "2012-01-01" "2012-01-02" "2012-01-03" [6] "2012-01-04" 

Here's a function to meet your specific request

itemizeDates <- function(startDate="12-30-11", endDate="1-4-12",                           format="%m-%d-%y") {   out <- seq(as.Date(startDate, format=format),               as.Date(endDate, format=format), by="days")     format(out, format) }  > itemizeDates(startDate="12-30-11", endDate="1-4-12") [1] "12-30-11" "12-31-11" "01-01-12" "01-02-12" "01-03-12" "01-04-12" 
like image 179
GSee Avatar answered Sep 20 '22 16:09

GSee