Date & Time in R
In this lesson, you will learn how R works with dates and time values.
Date and time data is extremely common in real-world datasets such as logs, transactions, events, timestamps, and time-series records. Understanding how to handle them correctly is essential for analysis.
Why Date & Time Handling Is Important
Date and time values allow you to:
- Track trends over time
- Calculate durations and differences
- Group and summarize data by time periods
- Build time-based reports and dashboards
Date and Time Classes in R
R has built-in classes to represent date and time values.
The most common ones are:
- Date – stores calendar dates
- POSIXct – stores date and time as a timestamp
- POSIXlt – stores date and time as a list structure
Working with Dates Using as.Date()
The as.Date() function converts character strings into Date objects.
Dates must follow a recognizable format such as YYYY-MM-DD.
date1 <- as.Date("2025-01-15")
date1
Getting the Current Date
You can retrieve today’s date using the Sys.Date() function.
today <- Sys.Date()
today
Working with Date & Time Using Sys.time()
The Sys.time() function returns the current date and time.
It uses the POSIXct format, which is suitable for precise timestamps.
current_time <- Sys.time()
current_time
Extracting Date Components
You can extract parts of a date such as year, month, and day.
This is useful for grouping or filtering data.
date <- as.Date("2024-12-20")
year <- format(date, "%Y")
month <- format(date, "%m")
day <- format(date, "%d")
year
month
day
Calculating Differences Between Dates
R allows you to subtract dates to calculate durations.
The result is returned as a time difference object.
start_date <- as.Date("2024-01-01")
end_date <- as.Date("2024-01-10")
difference <- end_date - start_date
difference
Adding or Subtracting Days
You can easily add or subtract days from a date.
This is helpful when calculating deadlines or future dates.
future_date <- Sys.Date() + 7
past_date <- Sys.Date() - 30
future_date
past_date
Formatting Dates for Display
Dates can be formatted to improve readability.
This is especially important for reports and dashboards.
formatted_date <- format(Sys.Date(), "%d %B %Y")
formatted_date
Common Date & Time Mistakes
- Using incorrect date formats
- Mixing character strings and Date objects
- Ignoring time zones
- Not converting data types properly
📝 Practice Exercises
Exercise 1
Convert the string "2023-08-25" into a Date object.
Exercise 2
Find the number of days between two dates.
Exercise 3
Extract the year from today’s date.
Exercise 4
Add 15 days to the current date.
✅ Practice Answers
Answer 1
as.Date("2023-08-25")
Answer 2
as.Date("2024-01-15") - as.Date("2024-01-01")
Answer 3
format(Sys.Date(), "%Y")
Answer 4
Sys.Date() + 15
What’s Next?
In the next lesson, you will learn about Data Aggregation in R.
This will help you summarize and analyze data efficiently.