Creating a sequence of dates with a special format

微笑、不失礼 提交于 2020-08-03 09:14:57

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!