跳转到内容

R 编程/时间和日期

来自维基教科书,开放世界中的开放书籍

R 包含一组用于保存日期和时间信息的**对象类型**。也可以请求系统时间和日期。

许多时间和日期单位都被识别。它们包括

单位 符号 示例
4 位年份 %Y 1932
2 位年份 %y 84
数字月份 %m 03
完整月份 %B 一月
缩写月份 %b 一月
月份中的日期 %d 31
完整星期几 %A 星期三
缩写星期几 %a 星期三
小时(24 小时制) %H 16
分钟 %M 35
%S 52


默认格式为 yyyy-mm-dd hh:mm:ss 或 %Y-%m-%d %H:%M:%S

例如 2010-02-13 23:12:24


系统日期和时间

[编辑 | 编辑源代码]

要获取系统日期和时间

> Sys.time()
 [1] "2010-02-13 23:12:24 COT"
> format(Sys.time(),"%H %M")   # in a different format and without the date
 [1] "23 13"
> Sys.Date()
 [1] "2010-02-13"
> date()                       # returns the current date and time,
[1] "Wed Jul 18 10:59:42 2012"

将字符串转换为日期/时间对象

[编辑 | 编辑源代码]

将表示日期或时间的字符串转换为日期/时间对象。

> my.date <- as.Date("2010-12-30")
> print(my.date)
 [1] "2010-12-30"
> my.date2 <- as.Date("12/20/30", format="%m/%d/%y") # input date in a different format
> print(my.date2)
 [1] "2030-12-20"
> my.time <- strptime("12/20/30 14.34.35", format="%m/%d/%y %H.%M.%S") # input time and date
> print(my.time)
 [1] "2030-12-20 14:34:35"
> my.string <- as.character(Sys.time()) # convert a date/time object to a normal string
> print(my.string)
 [1] "2016-06-30 23:04:44"

从日期中提取信息

[编辑 | 编辑源代码]

获取星期几、月份以及自纪元开始以来的天数。

> weekdays(my.date) # Get a string representing the weekday of the specified date
[1] "Monday"
> months(my.date)
[1] "December" # Get the month as well
> my.date
[1] "2010-12-20"
> julian(my.date) # Get the integer number of days since the beginning of epoch
[1] 14963
attr(,"origin")
[1] "1970-01-01"

请注意,weekdays()months() 返回的结果使用的是本地语言。例如,如果将 R 设置为法语,则可以获取法语的星期几和月份[1] 

> require("lubridate")
> Sys.setlocale(locale="fr_FR.UTF-8")
[1] "fr_FR.UTF-8/fr_FR.UTF-8/fr_FR.UTF-8/C/fr_FR.UTF-8/fr_FR.UTF-8"
> mydate  <- ymd("2002-04-21")
> weekdays(mydate)
[1] "Dimanche"
> months(mydate)
[1] "avril"

生成日期序列

[编辑 | 编辑源代码]
> seq(from = as.Date("01/01/12", "%d/%m/%y"), to = as.Date("10/01/12","%d/%m/%y"), by = "day")
#create the 10 first days of January 2012
 [1] "2012-01-01" "2012-01-02" "2012-01-03" "2012-01-04" "2012-01-05" "2012-01-06"
 [7] "2012-01-07" "2012-01-08" "2012-01-09" "2012-01-10"

> seq(from = as.Date("20/01/12", "%d/%m/%y"), to = as.Date("20/12/12","%d/%m/%y"), by = "month")
#create the 20th of each month in 2012
 [1] "2012-01-20" "2012-02-20" "2012-03-20" "2012-04-20" "2012-05-20" "2012-06-20"
 [7] "2012-07-20" "2012-08-20" "2012-09-20" "2012-10-20" "2012-11-20" "2012-12-20"

> seq(from = as.Date("01/01/12", "%d/%m/%y"), to = as.Date("31/01/12","%d/%m/%y"), length.out = 16)
#create a sequence of every other day in january 2012
 [1] "2012-01-01" "2012-01-03" "2012-01-05" "2012-01-07" "2012-01-09" "2012-01-11"
 [7] "2012-01-13" "2012-01-15" "2012-01-17" "2012-01-19" "2012-01-21" "2012-01-23"
[13] "2012-01-25" "2012-01-27" "2012-01-29" "2012-01-31"
[编辑 | 编辑源代码]
华夏公益教科书