问题
I was wondering how I could create a sequence of dates in the following format: from "Jul 23 10:20"
to "Jul 30 10:25"
by "1"
day?
I tried the following without sucess:
seq.Date(as.Date("Jul 23 10:20"), as.Date("Jul 30 10:25"), length.out = 7)
回答1:
To preserve times you should convert to actual date-times, from which it is easy to build a sequence increasing by 1 day at a time. You can use strftime
to format this as you please.
strftime(seq(as.POSIXct("2020-07-23 10:20"), by = "1 day", length.out = 7), "%b %e %H:%M")
#> [1] "Jul 23 10:20" "Jul 24 10:20" "Jul 25 10:20" "Jul 26 10:20" "Jul 27 10:20"
#> [6] "Jul 28 10:20" "Jul 29 10:20"
回答2:
We can get the dates by converting to Date
format
format(seq(as.POSIXct("Jul 23 10:20", format = "%b %d %H:%M" ),
by = "1 day", length.out = 7), "%b %d %H:%M")
#[1] "Jul 23 10:20" "Jul 24 10:20" "Jul 25 10:20" "Jul 26 10:20" "Jul 27 10:20" "Jul 28 10:20" "Jul 29 10:20"
Or with lubridate
library(lubridate)
format(as.POSIXct("Jul 23 10:20", format = '%b %d %H:%M') + days(0:4), "%b %d %H:%M")
#[1] "Jul 23 10:20" "Jul 24 10:20" "Jul 25 10:20" "Jul 26 10:20" "Jul 27 10:20"
来源:https://stackoverflow.com/questions/63061620/creating-a-sequence-of-dates-with-a-special-format