跳轉到內容

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"
[編輯 | 編輯原始碼]
華夏公益教科書