Dates and Times in R

R BasicsDateTimeFree Lesson

Advertisement

Introduction

R provides extensive capabilities for handling dates and times. The lubridate package makes datetime operations intuitive.

Creating Dates

# Using as.Date
date1 <- as.Date("2024-01-15")
date2 <- as.Date("01/15/2024", format = "%m/%d/%Y")

# Using ISOdate
date3 <- ISOdate(2024, 1, 15)

# Current date
today <- Sys.Date()

Date Functions

library(lubridate)

date <- ymd("2024-01-15")

year(date)        # 2024
month(date)       # 1
day(date)         # 15
wday(date)        # Day of week (1-7)
yday(date)        # Day of year (1-366)

Creating DateTimes

library(lubridate)

# From string
dt <- ymd_hms("2024-01-15 10:30:00")

# Current datetime
now()

# From components
ymd_hms(20240115103000)

Date Arithmetic

library(lubridate)

date1 <- ymd("2024-01-01")
date2 <- ymd("2024-01-15")

date2 - date1                # Difference in days
date2 + days(5)              # Add days
date1 + weeks(2)             # Add weeks
date1 %+% months(1)          # Add months

Time Zones

library(lubridate)

# With timezone
dt <- ymd_hms("2024-01-15 10:00:00", tz = "UTC")
dt

# Convert timezone
with_tz(dt, "America/New_York")
force_tz(dt, "America/New_York")

Summary

Master dates and times with lubridate for efficient datetime manipulation in R.

Advertisement

Need Expert R Programming Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement