R浅谈时间格式
#返回当前值或者返回当前时间
# 返回当前日期
Sys.Date()
[1] "2019-02-28"
# 返回当前时间
> Sys.time()
[1] "2019-02-28 17:32:06 CST"
#时间、日期是向量,可以当成数字进行运算
as.Date(1000,"2019-2-28")
#output:[1] "2021-11-24"
# 进行加减运算
as.Date("2021-11-24")-as.Date("2019-2-28")
#output:Time difference of 1000 days
my_date <- as.Date("2019-2-28")
# 向量化运算
my_date+1:3
#output:[1] "2019-03-01" "2019-03-02" "2019-03-03"
#但是我们没有as.Time()函数,但是可以有as.POSIXlt()函数
as.POSIXlt("2019-2-18 17:39:55")
output:[1] "2019-02-18 17:39:55 CST"
#当时间或者日期不是标准化的时候,我们可以通过这样的方式使日期/时间得到解析
as.Date('2019.2.28',format='%Y.%m.%d')
output:[1]"2019-02-28"
as.POSIXlt('2019.2.28.17.40.55',format='%Y.%m.%d.%H.%M.%S')
output:[1] "2019-02-28 17:40:55 CST"
strptime('2019.2.28.17.40.55',format='%Y.%m.%d.%H.%M.%S')
output:[1]"2019-02-28 17:40:55 CST"
# 将时间解析为数据框是一个更加美妙的例子
datetimes <- data.frame(date=c(20150601,20151225),time=c(92325,150621))
datetimes
output:
date time
1 20150601 092325
2 20151225 150621
datetimes$time <- sprintf('%06d',datetimes%time)
full_time <- paste0(datetimes$date,datetimes$time)
full_time
[1] "20150601092325" "20151225150621"
> strptime(date_full,format="%Y%m%d%H%M%S")
[1] "2015-06-01 09:23:25 CST" "2015-12-25 15:06:21 CST"
#时间格式转化为文本格式
my_date <- as.Date("2019-2-28")
char_time <- as.character(my_date)
char_time+3
# 显示错误
as.character(char_time,format="%Y.%m.%d")
output:[1]"2019.02.28"
#用difftime()函数可以计算相关的秒数、分钟数、小时数、天数、周数
> now <- Sys.time()
> myTime <- strptime("2017-02-01 12:00:08", format = "%Y-%m-%d %H:%M:%S")
> difftime(now, myTime)
Time difference of 25.95226 days
> difftime(now, myTime, units = "weeks")
Time difference of 3.707466 weeks
> difftime(now, myTime, units = "days")
Time difference of 25.95226 days
> difftime(now, myTime, units = "hours")
Time difference of 622.8543 hours
> difftime(now, myTime, units = "mins")
Time difference of 37371.26 mins
> difftime(now, myTime, units = "secs")
Time difference of 2242275 secs
其他日期相关函数
weekdays()取日期对象所处的周几;
months()取日期对象的月份;
quarters()取日期对象的季度;
> mydate <- Sys.Date()
> mydate
[1] "2017-02-27"
> weekdays(mydate)
[1] "星期一"
> months(mydate)
[1] "二月"
> quarters(mydate)
[1] "Q1"