lubridate
Functions in R
Learn to parse, manipulate, and reason about dates and times using the lubridate package: ymd(), mdy(), dmy(), and more.
Why Are Dates So Tricky?
Dates come in many formats: "2024-03-15", "March 15, 2024", "15/03/2024". R's base functions often misinterpret these. The lubridate package solves this by letting you tell R the order of components: year, month, and day.
What is lubridate?
Strings vs. Date Objects
A character string like "2024-03-15" is just text: R cannot do math on it. A Date object stores the date internally as a number, enabling subtraction, comparison, and extraction of components.
The Core Parsing Functions
The function name tells R the order of the components in your string. Each letter stands for: y = year, m = month, d = day.
"2024-03-15"
"2024/03/15"
"20240315"
"03-15-2024"
"March 15, 2024"
"3/15/24"
"15-03-2024"
"15 March 2024"
"15/03/24"
The Golden Rule
Flexible Separators
lubridate doesn't care about separators. Dashes, slashes, spaces, commas, or even no separator at all: as long as the order matches the function name, it works.
ymd vs mdy vs dmy
| Feature | ymd() | mdy() | dmy() |
|---|---|---|---|
| Order | Year, Month, Day | Month, Day, Year | Day, Month, Year |
| Common in | ISO standard, databases | USA | Europe, most of world |
| Example input | "2024-03-15" | "03/15/2024" | "15-03-2024" |
| Output | 2024-03-15 (same Date object) | ||
Adding Time: ymd_hms()
Append _hms, _hm, or _h to any parsing function to include time components: h = hours, m = minutes, s = seconds.
How to Apply: Step by Step
Example 1: Simple Parsing
You have the string "2024-07-04". Which function should you use?
Example 2: US-Format Dates
A dataset has dates like "July 4, 2024" and "12/25/2023". How do we parse them?
Example 3: European Format with Time
A log file has timestamps like "15/03/2024 14:30:00". The day comes first (European format), and there's a time component.
Extracting Components
Once you have a Date object, lubridate provides accessor functions to pull out individual parts.
Date Arithmetic
lubridate lets you add and subtract time using helper functions like days(), months(), and years().
Common Mistakes
Question 1 of 5
Which function would you use to parse the string "July 4, 2024"?
Question 2 of 5
What does ymd("20231225") return?
Question 3 of 5
A European dataset contains dates like "25/12/2023". Which function correctly parses this as December 25, 2023?
Question 4 of 5
You want to parse "2024-03-15 09:45:30" including the time. Which function should you use?
Question 5 of 5
What does month(ymd("2024-08-20")) return?