Hadley Wickham大神的力作。lubridate包讓時(shí)間數(shù)據(jù)的運(yùn)算變得極為簡便。
string轉(zhuǎn)time
從字符串到時(shí)間格式使用ymd()系列函數(shù)。只要字符串中是按照‘年 - 月- 日’順序排列,只要格式不是太糟亂,函數(shù)就能進(jìn)行正確地parse。
ymd(..., quiet = FALSE, tz = NULL, locale = Sys.getlocale("LC_TIME"),
truncated = 0)
#tz=NULL時(shí),輸出Date格式,否則輸出指定時(shí)區(qū)的POSIXct格式。
#truncated不為0時(shí),也可以分析截短的(truncated)日期字符串
> ymd('1926 08./17') #糟亂格式
[1] "1926-08-17"
> ymd('1926 08./',truncated = 2) #只有年月,日期默認(rèn)
[1] "1926-08-01"
> ymd('1926 ./',truncated = 2) #只有年,月日默認(rèn)
[1] "1926-01-01"
ymd還可以改換順序排列為ydm myd mdy ydm ymd.
要進(jìn)一步精確時(shí)分秒的話,還有ymd_h 、ymd_hm 、ymd_hms函數(shù)。
> ymd_h('192608/17 21')
[1] "1926-08-17 21:00:00 UTC"
> ymd_hms('192608/17 21 34 08')
[1] "1926-08-17 21:34:08 UTC"
time轉(zhuǎn)string
time格式要轉(zhuǎn)化為string,首先要提供一個(gè)模板(format)。lubridate可以接受一個(gè)字符串作為format,輸出一個(gè)轉(zhuǎn)換函數(shù)。這個(gè)新的轉(zhuǎn)換函數(shù)能接受time數(shù)據(jù),輸出等于format的字符串。
stamp_date和stamp_time則各自專精于日期和時(shí)間的轉(zhuǎn)換。
> fmt <- 'Recorded on Sunday, Jan 1, 2008 3:15 pm' #字符串format
> stamp.fmt <- stamp(fmt) #生成轉(zhuǎn)換函數(shù)
Multiple formats matched: "Recorded on Sunday, %Om %d, %Y %H:%M %Op"(1), "Recorded on Sunday, %Om %d, %Y %H:%M pm"(1), "Recorded on Sunday, Jan %Om, %Y %d:%H pm"(1), "Recorded on Sunday, Jan %d, %Y %Om:%H pm"(1), "Recorded on Sunday, Jan %m, %Y %d:%H pm"(1), "Recorded on Sunday, Jan %d, %Y %m:%H pm"(1)
Using: "Recorded on Sunday, %Om %d, %Y %H:%M %Op"
> stamp.fmt(x) #轉(zhuǎn)換
[1] "Recorded on Sunday, 02 23, 2018 19:54 下午"
時(shí)間差數(shù)據(jù)
Duration類
按照秒計(jì)算,每天均為24小時(shí),每年均為365天,不考慮閏年。這種時(shí)間差數(shù)據(jù)的格式可以用duration()函數(shù)生成,或用dyears等wrapper生成。但沒有dmonths,有dweeks。
today()函數(shù)輸出當(dāng)前的date數(shù)據(jù)。
as.period()函數(shù)能夠轉(zhuǎn)化其他時(shí)間差格式數(shù)據(jù)為period格式。
> d=duration(second = 3, minute = 1.5, hour = 2, day = 6, week = 1)
> today()+d
[1] "2018-03-08 02:01:33 UTC"
> today() + dweeks(1:6)
[1] "2018-03-02" "2018-03-09" "2018-03-16" "2018-03-23" "2018-03-30" "2018-04-06"
Period類
考慮了閏年等的影響。數(shù)據(jù)格式函數(shù)為period(),years()等。同樣沒有months,有weeks。
as.period()是相應(yīng)的轉(zhuǎn)化函數(shù)。
interval類
這個(gè)類必須有精確指定的首尾日期才能計(jì)算出來。
%--%是interval()的另一種寫法。
%within%可以檢驗(yàn)?zāi)硞€(gè)日期是否在interval之內(nèi),輸出邏輯值。
> interval(ymd('19260817'),today())
[1] 1926-08-17 UTC--2018-02-23 UTC
> a = interval(ymd('19260817'),today())
> as.period(a)
[1] "91y 6m 6d 0H 0M 0S"
> ymd('19260817') %--% today()
[1] 1926-08-17 UTC--2018-02-23 UTC
> ymd('2008 08.08') %within% a
[1] TRUE
時(shí)區(qū)
略
其他函數(shù)
如round_date,floor_date,ceiling_date。暫略。