# Parsing dates and times

install.packages("lubridate")
library(lubridate)
ymd("20150904")
ymd("2015-9-4")
ymd("2015/9/04")
dmy("04/09/15")
ymd_hms("2011-06-04 12:00:00")
x = ymd_hms("2011-08-10 14:05:08", tz = "Pacific/Auckland")
class(x)

# Setting and Extracting information

second(x)
minute(x)
hour(x)
day(x)
month(x)
year(x)
wday(x,label = T)
yday(x)
week(x)

# Time Zones

#奥克兰9点电话会议，求芝加哥几点开
meeting <- ymd_hms("2011-07-01 09:00:00", tz = "Pacific/Auckland")
with_tz(meeting, "America/Chicago")

#芝加哥如果误认为9点开，那么奥克兰接到电话的时间
mistake <- force_tz(meeting, "America/Chicago")
with_tz(mistake, "Pacific/Auckland")

# Time Intervals

arrive <- ymd_hms("2011-06-04 12:00:00", tz = "Pacific/Auckland")
leave <- ymd_hms("2011-08-10 14:00:00", tz = "Pacific/Auckland")
auckland <- interval(arrive, leave)
auckland <- arrive %--% leave
auckland
jsm <- interval(ymd(20110720, tz = "Pacific/Auckland"), ymd(20110831, tz = "Pacific/Auckland"))
#if trival overlap
auckland
jsm
lubridate::setdiff(auckland, jsm)

Other functions that work with intervals include int_start, int_end, int_flip, int_shift, int_aligns, union, intersect, setdiff, and %within%.

# Arithmetic with date times

- period
- duration

# period
minutes(2)
years(1)
# duration
dminutes(2)
dyears(1)   #always 365 days
# regular year
leap_year(2011)
leap_year(2000)

ymd(20110101) + dyears(1)
## [1] "2012-01-01 UTC"
ymd(20110101) + years(1)
## [1] "2012-01-01 UTC"
leap_year(2012)  ## leap year
## [1] TRUE
ymd(20120101) + dyears(1)
## [1] "2012-12-31 UTC"
ymd(20120101) + years(1)
## [1] "2013-01-01 UTC"

meeting <- ymd_hms("2011-07-01 09:00:00", tz = "Pacific/Auckland")
meetings <- meeting + weeks(0:5)
jsm <- interval(ymd(20110720, tz = "Pacific/Auckland"), ymd(20110831, tz = "Pacific/Auckland"))
meeting
meetings
jsm
meetings %within% jsm

arrive <- ymd_hms("2011-06-04 12:00:00", tz = "Pacific/Auckland")
leave <- ymd_hms("2011-08-10 14:00:00", tz = "Pacific/Auckland")
auckland <- interval(arrive, leave)
auckland
#days i stay
auckland/edays(1)
#minutes i stay
auckland/eminutes(1)

auckland%/%months(1)
auckland%%months(1)
as.period(auckland%%months(1))
as.period(auckland)


# Others

jan31 <- ymd("2013-01-31")
jan31 + months(0:11)

floor_date(jan31, "month") + months(0:11) + days(31)

jan31 %m+% months(0:11)


# Vectorization

last_day <- function(date) {
ceiling_date(date, "month") - days(1)
}
last_day(jan31)

lubridate

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120