data science tutorials and snippets prepared by greysweater42
it’s an R package that makes working with dates easy
because in base R working with dates may be a little bit daunting
the only disadvantage is performance, so use it for small datasets only
Load the package
library(lubridate)
## Warning in system("timedatectl", intern = TRUE): running command 'timedatectl'
## had status 1
Convert a string to class Date
:
# the base way
d <- as.Date("2017-03-03")
class(d)
## [1] "Date"
# the lubridate way
d <- ymd("2017-03-03")
class(d)
## [1] "Date"
Extract year, month and day
year(d)
## [1] 2017
month(d)
## [1] 3
day(d)
## [1] 3
You can also modify the date on the fly:
year(d) <- 1410
month(d) <- 7
day(d) <- 15
print(d)
## [1] "1410-07-15"
class(d)
## [1] "Date"
now
, the same as datetime.now()
in Python’s datetime package:
# the base way
n <- Sys.time()
# the lubridate way
n <- now()
Extracting hour, minute and second
hour(n)
## [1] 13
minute(n)
## [1] 42
second(n)
## [1] 24.31276
Days of the week
wday(d) # numbering starts from Sunday! you can adjust it, have a look at ?wday
## [1] 1
Adding / subtracting dates:
print(d)
## [1] "1410-07-15"
d + years(1) # yearS - plural form
## [1] "1411-07-15"
d - months(2)
## [1] "1410-05-15"