覆盖常用的时间处理操作,如:

  • 字符串转日期
  • 日期转字符串
  • 生成指定时间间隔的序列数据

生成间隔时序vector

timeRange <- function(starttime, endtime, step="15 mins", inputFormat='%Y%m%d%H%M%S', outputFormat='%Y%m%d%H%M%S'){
# 转换成POSIXlt格式
start_slice_p <- strptime(starttime, inputFormat)
end_slice_p <- strptime(endtime, inputFormat)
# 生成指定间隔的序列
seq_series <- seq.POSIXt(from=start_slice_p,to=end_slice_p,by=step)
# 再转成指定的字符串形式
output_seq <- as.character(seq_series,outputFormat)
return(output_seq)
}

年、月间隔

年间隔

timeRange(starttime = "2011-01-01 15:00:00", endtime = "2015-01-01 15:00:00", step = "2 years", 
inputFormat = "%Y-%m-%d %H:%M:%S", outputFormat = "%Y-%m-%d")
  1. '2011-01-01'
  2. '2013-01-01'
  3. '2015-01-01'

月间隔

timeRange(starttime = "2011-05-01 15:00:00", endtime = "2012-01-01 15:00:00", step = "1 months", 
inputFormat = "%Y-%m-%d %H:%M:%S", outputFormat = "%Y%m")
  1. '201105'
  2. '201106'
  3. '201107'
  4. '201108'
  5. '201109'
  6. '201110'
  7. '201111'
  8. '201112'
  9. '201201'

周、天间隔

周间隔

timeRange(starttime = "2020-04-29", endtime = "2020-05-31", step = "1 weeks", 
inputFormat = "%Y-%m-%d", outputFormat = "%Y%m%d")
  1. '20200429'
  2. '20200506'
  3. '20200513'
  4. '20200520'
  5. '20200527'

天间隔

timeRange(starttime = "2020-04-29", endtime = "2020-05-05", step = "2 days", 
inputFormat = "%Y-%m-%d", outputFormat = "%Y%m%d")
  1. '20200429'
  2. '20200501'
  3. '20200503'
  4. '20200505'

时分秒间隔

小时间隔

timeRange(starttime = "2020-04-29 15:15:15", endtime = "2020-04-29 17:40:40", step = "2 hours", 
inputFormat = "%Y-%m-%d %H:%M:%S", outputFormat = "%Y-%m-%d %H:%M:%S")
  1. '2020-04-29 15:15:15'
  2. '2020-04-29 17:15:15'

分钟间隔

timeRange(starttime = "2020-04-29 15:15:15", endtime = "2020-04-29 16:40:40", step = "20 mins", 
inputFormat = "%Y-%m-%d %H:%M:%S", outputFormat = "%Y-%m-%d %H:%M:%S")
  1. '2020-04-29 15:15:15'
  2. '2020-04-29 15:35:15'
  3. '2020-04-29 15:55:15'
  4. '2020-04-29 16:15:15'
  5. '2020-04-29 16:35:15'

秒间隔

timeRange(starttime = "2020-04-29 15:15:15", endtime = "2020-04-29 15:40:40", step = "60 secs", 
inputFormat = "%Y-%m-%d %H:%M:%S", outputFormat = "%Y-%m-%d %H:%M:%S")
  1. '2020-04-29 15:15:15'
  2. '2020-04-29 15:16:15'
  3. '2020-04-29 15:17:15'
  4. '2020-04-29 15:18:15'
  5. '2020-04-29 15:19:15'
  6. '2020-04-29 15:20:15'
  7. '2020-04-29 15:21:15'
  8. '2020-04-29 15:22:15'
  9. '2020-04-29 15:23:15'
  10. '2020-04-29 15:24:15'
  11. '2020-04-29 15:25:15'
  12. '2020-04-29 15:26:15'
  13. '2020-04-29 15:27:15'
  14. '2020-04-29 15:28:15'
  15. '2020-04-29 15:29:15'
  16. '2020-04-29 15:30:15'
  17. '2020-04-29 15:31:15'
  18. '2020-04-29 15:32:15'
  19. '2020-04-29 15:33:15'
  20. '2020-04-29 15:34:15'
  21. '2020-04-29 15:35:15'
  22. '2020-04-29 15:36:15'
  23. '2020-04-29 15:37:15'
  24. '2020-04-29 15:38:15'
  25. '2020-04-29 15:39:15'
  26. '2020-04-29 15:40:15'

注意点

  • 区间左闭右闭
  • 时间格式要和输入的变量一致
  • step要注意格式,s不要忘记

                                2020-04-29 于南京市江宁区九龙湖