二、日期时间成分
1 时间成分获取
> datetime <- ymd_hms("2016-07-08 12:34:56")
> year(datetime)
[1] 2016
> month(datetime)
[1] 7
> mday(datetime)
[1] 8
> yday(datetime)
[1] 190
> wday(datetime)
[1] 6
> hour(datetime)
[1] 12
> minute(datetime)
[1] 34
> second(datetime)
[1] 56
- 对于
month() 和wday() 函数,你可以设置label = TRUE 来返回月份名称和星期数的缩写,还可以设置abbr = FALSE 来返回全名 - 中文系统条件下
> month(datetime,label = TRUE)
[1] 七月
12 Levels: 一月 < 二月 < 三月 < 四月 < ... < 十二月
> month(datetime,label = TRUE,abbr = FALSE)
[1] 七月
12 Levels: 一月 < 二月 < 三月 < 四月 < ... < 十二月
> wday(datetime,label = TRUE)
[1] 周五
7 Levels: 周日 < 周一 < 周二 < 周三 < ... < 周六
> wday(datetime,label = TRUE,abbr = FALSE)
[1] 星期五
7 Levels: 星期日 < 星期一 < ... < 星期六
> Sys.setlocale("LC_TIME", "English")
[1] "English_United States.1252"
> month(datetime,label = TRUE,abbr = FALSE)
[1] July
12 Levels: January < February < ... < December
> wday(datetime,label = TRUE,abbr = FALSE)
[1] Friday
7 Levels: Sunday < Monday < ... < Saturday
> month(datetime,label = TRUE)
[1] Jul
12 Levels: Jan < Feb < Mar < Apr < ... < Dec
> wday(datetime,label = TRUE)
[1] Fri
7 Levels: Sun < Mon < Tue < Wed < ... < Sat
2 时间计算(更改)
update(time,year,month,mday,hour)
> datetime
[1] "2016-07-08 12:34:56 UTC"
> year(datetime) <- 2020
> month(datetime) <- 01
> hour(datetime) <- hour(datetime) + 1
> datetime
[1] "2020-01-08 13:34:56 UTC"
> update(datetime, year = 2020, month = 2, mday = 2, hour = 2)
[1] "2020-02-02 02:34:56 UTC"
> ymd("2015-02-01") %>%
+ update(hour = 25)
[1] "2015-02-02 01:00:00 UTC"
> ymd("2015-02-01") %>%
+ update(mday = 28)
[1] "2015-02-28"
3 时期
dseconds 、dminutes 、dhours 、ddays 、dweeks 、dyears - 以秒计算,不考虑夏时制和闰年
> ddays()
[1] "86400s (~1 days)"
> dyears(1) + dweeks(12) + dhours(15)
[1] "38869200s (~1.23 years)"
> one_pm <- ymd_hms(
+ "2016-03-12 13:00:00",
+ tz = "America/New_York"
+ )
> one_pm+ddays(1)
[1] "2016-03-13 14:00:00 EDT"
3 阶段
- 考虑了夏时制和闰年
seconds 、minutes 、hours 、days 、weeks 、years
> days(50) + hours(25) + minutes(2)
[1] "50d 25H 2M 0S"
> one_pm+days(1)
[1] "2016-03-13 13:00:00 EDT"
4 时区
> Sys.timezone()
[1] "Asia/Taipei"
> OlsonNames()
[1] "Africa/Abidjan"
[2] "Africa/Accra"
[3] "Africa/Addis_Ababa"
> (x1 <- ymd_hms("2015-06-01 12:00:00", tz = "America/New_York"))
[1] "2015-06-01 12:00:00 EDT"
> (x2 <- ymd_hms("2015-06-01 18:00:00", tz = "Europe/Copenhagen"))
[1] "2015-06-01 18:00:00 CEST"
> (x3 <- ymd_hms("2015-06-02 04:00:00", tz = "Pacific/Auckland"))
[1] "2015-06-02 04:00:00 NZST"
> x1-x3
Time difference of 0 secs
> x2-x3
Time difference of 0 secs
|