RNote102---时间处理
原创
©著作权归作者所有:来自51CTO博客作者维格堂406小队的原创作品,请联系作者获取转载授权,否则将追究法律责任
覆盖常用的时间处理操作,如:
- 字符串转日期
- 日期转字符串
- 生成指定时间间隔的序列数据
生成间隔时序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")
- '2011-01-01'
- '2013-01-01'
- '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")
- '201105'
- '201106'
- '201107'
- '201108'
- '201109'
- '201110'
- '201111'
- '201112'
- '201201'
周、天间隔
周间隔
timeRange(starttime = "2020-04-29", endtime = "2020-05-31", step = "1 weeks",
inputFormat = "%Y-%m-%d", outputFormat = "%Y%m%d")
- '20200429'
- '20200506'
- '20200513'
- '20200520'
- '20200527'
天间隔
timeRange(starttime = "2020-04-29", endtime = "2020-05-05", step = "2 days",
inputFormat = "%Y-%m-%d", outputFormat = "%Y%m%d")
- '20200429'
- '20200501'
- '20200503'
- '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")
- '2020-04-29 15:15:15'
- '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")
- '2020-04-29 15:15:15'
- '2020-04-29 15:35:15'
- '2020-04-29 15:55:15'
- '2020-04-29 16:15:15'
- '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")
- '2020-04-29 15:15:15'
- '2020-04-29 15:16:15'
- '2020-04-29 15:17:15'
- '2020-04-29 15:18:15'
- '2020-04-29 15:19:15'
- '2020-04-29 15:20:15'
- '2020-04-29 15:21:15'
- '2020-04-29 15:22:15'
- '2020-04-29 15:23:15'
- '2020-04-29 15:24:15'
- '2020-04-29 15:25:15'
- '2020-04-29 15:26:15'
- '2020-04-29 15:27:15'
- '2020-04-29 15:28:15'
- '2020-04-29 15:29:15'
- '2020-04-29 15:30:15'
- '2020-04-29 15:31:15'
- '2020-04-29 15:32:15'
- '2020-04-29 15:33:15'
- '2020-04-29 15:34:15'
- '2020-04-29 15:35:15'
- '2020-04-29 15:36:15'
- '2020-04-29 15:37:15'
- '2020-04-29 15:38:15'
- '2020-04-29 15:39:15'
- '2020-04-29 15:40:15'
注意点
- 区间左闭右闭
- 时间格式要和输入的变量一致
- step要注意格式,s不要忘记
2020-04-29 于南京市江宁区九龙湖