获取当前的日期和时间
在编程中,为了获得当前的日期和时间,有两个常用的函数,这两个函数以 Sys 开头,返回的时间受到操作系统区域设置的影响,因此,返回的时间采用本地格式,符合本地的阅读习惯:
> Sys.Date()
[1] "2020-03-18"
> class(Sys.Date())
[1] "Date"
> Sys.time()
[1] "2020-03-18 09:07:53 CST"
> class(Sys.time())
[1] "POSIXct" "POSIXt"
R 还有一个函数 date(),用于返回当前时间对应的文本
> date()
[1] "Wed Mar 18 09:12:28 2020"
文本 >> 日期和时间
-
as.Date()
把文本转换为日期as.Date(x, format)
format
参数用于指定输入的格式,常用的日期格式符号是:%y
:两位数字表示的年份(00-99),不带世纪,例如,数值是 18,格式%y,表示 2018 年%Y
:四位数字表示的年份(0000-9999)%m
:两位数字的月份,取值范围是 01-12,或 1-12%d
:月份中的天,取值范围是 01-31%e
:月份中的天,取值范围是 1-31%b
:月份的缩写(Jan、Feb、Mar 等)%B
:月份的全名(January、February 、March 等)%a
:星期的缩写(Mon、Tue、Wed、Thur、Fri、Sat、Sun)%A
:星期的全名(Monday、Tuesday、Wednesday 等)
date_vec <- c("2020-01-01", "2020-12-31") date_vec_format <- as.Date(date_vec, format = "%Y-%m-%d")
-
strptime()
解析日期函数
strptime()
,是string parse time
的简称,返回POSIXlt
日期。在解析日期时,必须指定文本和日期对应的位置,日期的格式使用%+字母
来指定。format(x, format = "", tz = "")
参数
tz
是时区(time zone)
,默认值是空,在解析时,如果不指定时区,R 会调用Sys.timezone
日期格式和 format()函数相同,常用的时间格式符号是:
%H
: 小时(24 小时制)%I
: 小时(12 小时制)%p
: 对于 12 小时制,指定上午(AM)或下午(PM)%M
: 分钟%S
: 秒
cur_date <- date() cur_date_parse <- strptime(current_date, format = "%a %b %d %H:%M:%S %Y")
日期和时间 >> 文本
-
format()
把日期转换为文本对日期进行格式化,转换为可读的文本,
format()
函数的定义是:format(x, format = "", tz = "")
x 是日期参数,
format
是输出的格式,tz
是时区,该函数按照指定的格式输出文本:today <- Sys.Date() mydate <- format(today,format='%Y-%m-%d')
-
strftime()
格式化日期函数
strftime()
,是string formated time
的简称,用于把时间转换为字符串strptime(x, format, tz = "")
该函数和
format()
函数的功能和使用方式几乎完全相同。today <- Sys.Date() mydate <- strftime(today,format='%Y-%m-%d')
日期的比较
由于 POSIXct
类是以秒为单位来计算时间,Date
类是以天为单位类计算日期,这意味着可以在日期值上执行比较运算和算术运算:
- 将数字和
Date
类相加,增加或减少相应的天数 - 将数字和
POSIXct
类相加,增加或减少相应的秒数
-
时间和数字相加
时间以秒为单位
> time1 <- Sys.time() > print(time1) [1] "2018-05-08 13:16:36 CST" > print(time1+60*60) [1] "2018-05-08 14:16:36 CST"
日期以天为单位
> date1 <- Sys.Date() > print(date1) [1] "2018-05-08" > print(date1+1) [1] "2018-05-09"
-
时间比较
由于
Date
类和POSIXct
类实际上都是一个整数,可以直接比较大小date1 <- as.Date('2018-01-01') date2 <- as.Date('2018-02-01') if (date2 > date1) print ('gt')
总结
格式转换
文本 >> 日期和时间 | 日期和时间 >> 文本 |
---|---|
as.Date() 返回 Date 类型 | format() |
strptime() 返回 POSIXct 类型 | strftime() |