Learn tidyverse · 11/13

Time Travel in R: Dates and Times (lubridate)

7 min read

Welcome to the dimension of time! 🕰️

Handling dates and times is notoriously one of the most frustrating tasks in programming. Why? Because humans have made time complicated. We have leap years, months with different numbers of days, time zones that change offsets twice a year (Daylight Saving Time), and seconds that sometimes get added (leap seconds) just to keep our clocks in sync with the Earth's rotation.

In the old days of R, we struggled. But today, we use lubridate. It’s a package specifically designed to make working with dates and times... well, tidy.

Fun Fact: The year 1752 was a short year for the British Empire. They switched from the Julian to the Gregorian calendar, causing September 2nd to be immediately followed by September 14th. Imagine the payroll bugs that would cause today!


0. Getting Started

As of tidyverse 2.0.0, lubridate is part of the core tidyverse. However, if you are running an older version, you might need to load it explicitly.

Installation & Setup

r
# If you haven't installed the tidyverse yet:
install.packages("tidyverse")

# Load the core tidyverse (includes lubridate in modern versions)
library(tidyverse)

# If you see a message saying lubridate wasn't loaded, run:
library(lubridate)

1. Parsing Dates: Turning Strings into Datetime Objects

The Problem

Data usually comes to us as strings (text). You might see "2023-10-31" or "10/31/2023". To a computer, "10/01/2023" comes before "02/01/2023" if it treats them like words in a dictionary (1 comes before 2). We need to convert this text into an actual Date object so R understands chronological order.

The Solution: The "Order" Helpers

lubridate provides helper functions named after the order in which the Year (y), Month (m), and Day (d) appear in your string.

  • ymd(): Year, Month, Day
  • mdy(): Month, Day, Year
  • dmy(): Day, Month, Year

These functions are smart—they can handle hyphens, slashes, or even no separators at all.

Industry Example

Imagine you have a CSV dump of user sign-ups with messy formatting.

r
raw_dates <- c("2023-12-25", "2023/12/26", "20231227")
us_style  <- c("12-25-2023", "12/26/2023")
eu_style  <- c("25-12-2023", "26.12.2023")

# Parsing ISO style (Year-Month-Day)
# Under the hood: Creates a "Date" object
parsed_iso <- ymd(raw_dates)
print(parsed_iso)
# Output: [1] "2023-12-25" "2023-12-26" "2023-12-27"

# Parsing US style (Month-Day-Year)
parsed_us <- mdy(us_style)
print(parsed_us)
# Output: [1] "2023-12-25" "2023-12-26"

# Parsing Time (Hours, Minutes, Seconds)
# Just add h, m, and s to the function name!
timestamp <- ymd_hms("2023-01-01 14:30:59")
print(timestamp)

Pro Tip: In the industry, ISO 8601 (YYYY-MM-DD) is the gold standard. If you create data, always use this format. If you receive data, ymd() is your best friend.


2. Extracting Components: Getting Years, Months, and Days

The Problem

You have a full timestamp: 2023-10-31 14:00:00. Your boss asks, "How many sales did we make on Tuesdays?" or "Compare sales in October vs November." You don't need the exact second; you need a specific component of that time.

The Solution: Accessor Functions

lubridate allows you to pull out parts of a date object as if you were asking "What time is it?"

  • year(): Extracts the year.
  • month(): Extracts the month.
  • mday(): Day of the month.
  • wday(): Day of the week (Crucial for business analytics).

Code Example

r
datetime <- ymd_hms("2023-10-31 23:59:00")

# Basic extraction
print(year(datetime))  # 2023
print(month(datetime)) # 10

# Getting the Day of the Week
# The 'label = TRUE' argument is super useful for reporting!
# It returns "Tue" instead of "3" (or whatever number Tuesday is).
print(wday(datetime, label = TRUE, abbr = FALSE)) 
# Output: Tuesday

Under the hood

When you run month(..., label=TRUE), R is actually converting the number into an ordered factor. This ensures that when you plot a chart, January appears before February, rather than sorting alphabetically where April would come first.


3. Time Math: Durations, Periods, and Intervals

The Problem

Time math is weird.
If you add 1 day to "January 31st," you get "February 1st."
If you add 1 month to "January 31st," what do you get? February 31st? (That doesn't exist).
If you add 1 day during a Daylight Saving Time switch, do you add 24 hours (ending up an hour off on the clock) or do you jump to the same time the next day?

lubridate splits time math into three concepts to solve this:

  1. Durations: Exact seconds (Physics time).
  2. Periods: Human units (Calendar time).
  3. Intervals: A specific span of time with a start and end point.

The Solution

A. Durations (Exact Seconds)

Use this when you are measuring physical processes (e.g., battery life, server uptime). Durations always equal 60 seconds * 60 minutes, etc.

r
# Add exactly 86400 seconds (one standard day)
now <- ymd_hms("2024-03-09 13:00:00") # Day before DST change in US
future_duration <- now + ddays(1) # Note the 'd' for duration

B. Periods (Human/Calendar Time)

Use this for business logic. "Subscribe for 1 month." "Meet same time tomorrow."

r
# Add 1 calendar day
future_period <- now + days(1) 

# The Leap Year/Month Issue
# what happens if we add 1 month to Jan 31?
jan31 <- ymd("2023-01-31")
print(jan31 + months(1)) 
# Output: NA (Because Feb 31 doesn't exist)

# To fix this "overflow", we use %m+%
print(jan31 %m+% months(1))
# Output: "2023-02-28" (Rolls back to the last valid day)

C. Intervals (Start -> End)

An interval is a bridge between two specific points in time. It is the most accurate way to calculate "How long has it been?"

r
start_date <- ymd("2023-01-01")
end_date   <- ymd("2023-12-31")

# Create an interval using the %--% operator
my_interval <- start_date %--% end_date

# Check if a specific date falls inside this interval
check_date <- ymd("2023-06-15")
print(check_date %within% my_interval) 
# Output: TRUE

4. Working with Time Zones and Rounding Dates

The Problem (Time Zones)

Your server logs are in UTC (Coordinated Universal Time). Your user is in Nepal. Your analyst is in New York. If you don't handle time zones, your "Daily Report" will include data from the wrong day depending on who looks at it.

Real Life Scenario: You schedule a job for 2 AM on Sunday. During the Fall DST change, 2 AM happens twice. During Spring, 2 AM never happens. 🤯

The Solution: with_tz() and force_tz()

  1. with_tz(): Changes the clock face (converts time). The moment in history is the same, but the label changes. (e.g., 09:00 UTC -> 04:00 EST).
  2. force_tz(): Changes the underlying data. Use this when you imported data assuming it was UTC, but realized later it was actually New York time.
r
utc_time <- ymd_hms("2023-06-01 12:00:00", tz = "UTC")

# Convert to Nepal Time for display (Nepal is UTC + 5:45)
nepal_time <- with_tz(utc_time, tz = "Asia/Kathmandu")
print(nepal_time)
# Output: "2023-06-01 17:45:00 +0545"

The Problem (Rounding)

You have data for every second (web clicks), but you want to plot a bar chart of clicks per hour or per week.

The Solution: floor_date()

This is arguably the most used function in data science aggregation. It rounds a date down to the nearest unit.

r
timestamps <- c(
  "2023-10-01 14:15:00",
  "2023-10-01 14:45:00",
  "2023-10-01 15:05:00"
)
ts_obj <- ymd_hms(timestamps)

# Group by Hour
hourly_bins <- floor_date(ts_obj, unit = "hour")
print(hourly_bins)
# Output: 
# "2023-10-01 14:00:00 UTC" 
# "2023-10-01 14:00:00 UTC" (Both 14:xx became 14:00)
# "2023-10-01 15:00:00 UTC"

Practical Application: In a dplyr pipeline, you often mutate(date_month = floor_date(date_col, "month")) then group_by(date_month) to get monthly summaries.


Summary of Essential Functions

Concept Function Usage
Parsing ymd(), mdy_hms() Convert text string to Date object.
Extracting year(), month(), wday() Get specific parts of a date.
Math days(), months() Add calendar periods (human time).
Math %m+% Add months without getting "NA" on the 31st.
Rounding floor_date() Bucket dates (e.g., "round down to nearest week").
Zones with_tz() View the same time in a different time zone.

📚 References & Further Reading

Challenge

You are a data analyst for a global e-commerce platform. You need to analyze transaction data from a recent week-long "Black Friday" promotion to understand weekend shopping patterns. The timestamps were recorded in local time zones.

Your task is to process this data and produce a summary report counting the number of transactions that occurred on a weekend (Saturday or Sunday) for each week of the sale.

Data:
You are provided with two vectors: transaction_strings and timezones.

Requirements:

  1. Combine the transaction_strings and timezones vectors into a single tibble.
  2. Parse the transaction_strings into datetime objects. Then, use the timezones vector to correctly assign the time zone to each parsed datetime. Hint: The parsed time represents the local time; you need to assign its time zone context without shifting the time.
  3. Create a new column containing the transaction times converted to the "UTC" timezone for standardization.
  4. The official promotional period is defined as the interval from 2023-11-24 00:00:00 UTC to 2023-12-01 00:00:00 UTC.
  5. Filter the dataset to include only transactions that fall within this promotional interval.
  6. From the filtered data, identify the transactions that occurred on a weekend (Saturday or Sunday) based on their UTC time.
  7. Generate a final summary tibble that shows the count of these weekend transactions, grouped by the start of their week. The week should be rounded down to the nearest Sunday. The final tibble should have two columns: week_start and weekend_txn_count.

Expected result

Your final output should be a tibble named weekend_summary that contains two columns:

  1. week_start: A datetime column showing the first moment of the week (a Sunday at midnight) for which the transactions are aggregated.
  2. weekend_txn_count: An integer column with the total count of weekend transactions for that week.

The tibble should look exactly like this:

apache
# A tibble: 2 × 2
  week_start          weekend_txn_count
  <dttm>                          <int>
1 2023-11-19 00:00:00                 2
2 2023-11-26 00:00:00                 1
r

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.