R语言学习:数据结构8-日期和时间

来源:互联网 发布:html中调用js函数 编辑:程序博客网 时间:2024/06/06 12:32
日期和时间 date time
日期:Date 内部存储的是距离1970-01-01的天数。
相关函数:date(),Sys.Date(),weekdays(),months(),quarters()。
查看日期
#date
x <- date()    //查看当前系统日期和时间
class(x)    //字符型
x2 <- Sys.Date()    //系统日期
class(x2)    //日期类型
x3 <- as.Date("2016-02-17")    //存储为日期类型:年-月-日,"yyyy-mm-dd"。
class(x3)    //日期类型
weekdays(x3)
months(x3)
quarters(x3)
julian(x3)    //距离1970-01-01的天数
x4 <- as.Date("2015-02-17")
x3-x4
class(x3-x4)    //差分类型
as.numeric(x3-x4 )    //日期运算


时间:POSIXct、POSIXlt 内部存储的是距离1970-01-01的秒数,Sys.time()。
POSIXct:整数,常用于存入数据框。
POSIXlt:列表,还包括星期、年、月、日等信息。
查看时间
#time
y <- date()    //查看当前系统日期和时间
class(y)    //字符型
x <- Sys.time()    //系统时间
class(x)    //POSIXct型
x2 <- as.POSIXlt(x)
class(x2)    //POSIXlt类型
names(unclass(x2))    //查看lt中存了哪些变量
names(x2)    //显示NULL
x2$sec    //查看变量x2中的秒数
x3 <- as.POSIXct(x2)


字符类型转换为日期时间类型
as.Date("2016-02-17")    //特定格式转换
as.POSIXlt()    //特定格式转换
as.POSIXct()    //特定格式转换
x1 <- "Jan 1, 2015 01:01"
strptime(x1, "%B %d, %Y %H:%M")    //不同格式的字符串转换成日期时间

1 0