Lubridate is an R package that facilitates the manipulation and parsing of dates and times. It provides functions to work with date-time data in a more intuitive way. Here’s a cheat sheet for tasks using lubridate:
Installation
install.packages("lubridate")
library(lubridate)
Creating Date-Time Objects
Current Date and Time:
now()
Specific Date-Time:
ymd_hms("2022-01-01 12:30:45")
Extracting Components
Extract Year, Month, Day:
year(date)
month(date)
day(date)
Extract Hour, Minute, Second:
hour(datetime)
minute(datetime)
second(datetime)
Manipulating Dates
Adding/Subtracting Days:
date + days(5)
date - days(10)
Adding/Subtracting Months:
date + months(2)
date - months(3)
Date-Time Arithmetic
Difference in Days:
difftime(date1, date2, units = "days")
Difference in Weeks:
difftime(date1, date2, units = "weeks")
Formatting Dates
Format Date-Time:
format(date, "%Y-%m-%d %H:%M:%S")
Weekday Abbreviation:
wday(date, label = TRUE, abbr = TRUE)
Dealing with Time Zones
Set Time Zone:
with_tz(datetime, "America/New_York")
Get System Time Zone:
Sys.timezone()
Rounding and Truncating
Round to Nearest Minute:
round_date(datetime, "minute")
Truncate to Nearest Hour:
floor_date(datetime, "hour")
Periods and Durations
Create a Duration:
duration(days = 2, hours = 5, minutes = 30)
Add Duration to Date-Time:
date + duration(days = 3)
Working with Intervals
Create an Interval:
interval(start = ymd("2022-01-01"), end = ymd("2022-01-10"))
Check if Date-Time is in Interval:
date %within% interval
This cheat sheet covers some of the fundamental functions and operations provided by lubridate. For more detailed information and additional functions, refer to the lubridate documentation.