POSIXlt、Date是时间序列类型的索引类型,也是R的基础类型,有大量的操作可以方便的处理日期。
> as.POSIXlt('2016/04/05')
[1] "2016-04-05 CST"
详细参考:
> dts <- as.Date("20050101", '%Y%m%d') + seq(0,1000,15)
> dts
[1] "2005-01-01" "2005-01-16" "2005-01-31" "2005-02-15" "2005-03-02"
[6] "2005-03-17" "2005-04-01" "2005-04-16" "2005-05-01" "2005-05-16"
[11] "2005-05-31" "2005-06-15" "2005-06-30" "2005-07-15" "2005-07-30"
[16] "2005-08-14" "2005-08-29" "2005-09-13" "2005-09-28" "2005-10-13"
[21] "2005-10-28" "2005-11-12" "2005-11-27" "2005-12-12" "2005-12-27"
[26] "2006-01-11" "2006-01-26" "2006-02-10" "2006-02-25" "2006-03-12"
[31] "2006-03-27" "2006-04-11" "2006-04-26" "2006-05-11" "2006-05-26"
[36] "2006-06-10" "2006-06-25" "2006-07-10" "2006-07-25" "2006-08-09"
[41] "2006-08-24" "2006-09-08" "2006-09-23" "2006-10-08" "2006-10-23"
[46] "2006-11-07" "2006-11-22" "2006-12-07" "2006-12-22" "2007-01-06"
[51] "2007-01-21" "2007-02-05" "2007-02-20" "2007-03-07" "2007-03-22"
[56] "2007-04-06" "2007-04-21" "2007-05-06" "2007-05-21" "2007-06-05"
[61] "2007-06-20" "2007-07-05" "2007-07-20" "2007-08-04" "2007-08-19"
[66] "2007-09-03" "2007-09-18"
> str(dts)
Date[1:67], format: "2005-01-01" "2005-01-16" "2005-01-31" "2005-02-15" ...
日期Date加上一个整数n之后是n天之后,减法对应n天之前
dayWidth<-30
>
> buyDate<-as.Date('20170405','%Y%m%d')
> saleDate<-as.Date('20170509','%Y%m%d')
>
> buyDate
[1] "2017-04-05"
> saleDate
[1] "2017-05-09"
>
> oneYearBefore<-buyDate - dayWidth
> oneYearLater<-saleDate + dayWidth
>
> oneYearBefore
[1] "2017-03-06"
> oneYearLater
[1] "2017-06-08"
>
> x<-oneYearLater - oneYearBefore
> as.intdayWidth<-30
>
> buyDate<-as.Date('20170405','%Y%m%d')
> saleDate<-as.Date('20170509','%Y%m%d')
>
> buyDate
[1] "2017-04-05"
> saleDate
[1] "2017-05-09"
>
> oneYearBefore<-buyDate - dayWidth
> oneYearLater<-saleDate + dayWidth
>
> oneYearBefore
[1] "2017-03-06"
> oneYearLater
[1] "2017-06-08"
>
> x<-oneYearLater - oneYearBefore
> as.integer(x)
[1] 94
> dayWidth<-30
>
> buyDate<-as.Date('20170405','%Y%m%d')
> saleDate<-as.Date('20170509','%Y%m%d')
>
> buyDate
[1] "2017-04-05"
> saleDate
[1] "2017-05-09"
>
> oneYearBefore<-buyDate - dayWidth
> oneYearLater<-saleDate + dayWidth
>
> oneYearBefore
[1] "2017-03-06"
> oneYearLater
[1] "2017-06-08"
> dt <- as.Date("20050101", '%Y%m%d')
> dt
[1] "2005-01-01"
> format(dt,'%Y')
[1] "2005"
> format(dt,'%j')
[1] "001"
> as.integer(format(dt,'%j'))