Parsing Dates &
Time Zones in R
Learn to transform raw date strings into proper Date and POSIXct objects, handle common format codes, and navigate time zone conversions with confidence.
What Is Date Parsing?
When you import data into R, dates often arrive as plain character strings like "03/15/2024" or "January 5, 2021". R cannot do date arithmetic, sorting, or plotting on raw text. Parsing means converting those strings into structured date objects that R understands.
Why Does Parsing Matter?
R's Two Date/Time Types
The Format Code System
R uses format codes beginning with % to describe the structure of a date string. You pass these codes as the format argument to tell R how to read your string.
| Code | Meaning | Example |
|---|---|---|
| %Y | 4-digit year | 2024 |
| %m | Month (01-12) | 03 |
| %d | Day (01-31) | 15 |
| %B | Full month name | March |
| %H | Hour (00-23) | 14 |
| %M | Minute (00-59) | 30 |
| %S | Second (00-59) | 05 |
The Golden Rule of Parsing
Date vs POSIXct: When to Use Which
| Feature | Date | POSIXct |
|---|---|---|
| Stores time? | No | Yes |
| Time zone aware? | No | Yes |
| Internal storage | Days (integer) | Seconds (double) |
| Function | as.Date() | as.POSIXct() |
| Best for | Birthdays, fiscal dates | Timestamps, logs, events |
Understanding Time Zones
Step-by-Step Parsing Workflow
Example 1: Simple Date
Example 2: US Format with Time
Example 3: Named Month + Zone Conversion
The lubridate Shortcut
The lubridate package provides intuitive helper functions that auto-detect formats so you don't have to write % codes manually.
Two Time Zone Operations
Common Mistakes
Quick Reference Table
| Task | Base R | lubridate |
|---|---|---|
| Parse "2024-03-15" | as.Date(x, "%Y-%m-%d") | ymd(x) |
| Parse "03/15/2024" | as.Date(x, "%m/%d/%Y") | mdy(x) |
| Parse with time | as.POSIXct(x, format, tz) | mdy_hm(x, tz=...) |
| Convert zone | format(x, tz=...) | with_tz(x, ...) |
| Re-label zone | attr(x,"tzone") <- ... | force_tz(x, ...) |
| Today's date | Sys.Date() | today() |
| Current time | Sys.time() | now() |
Question 1 of 5
What class does as.Date("2024-01-15") return?
Question 2 of 5
Which format string correctly parses "15-Mar-2024"?
Question 3 of 5
Which lubridate function would you use to parse the string "25/12/2023" (day/month/year)?
Question 4 of 5
You have a POSIXct timestamp in "America/New_York" and want to see what time it is in London without changing the actual moment. Which function do you use?
Question 5 of 5
If as.POSIXct("03/15/2024", format = "%d/%m/%Y") returns NA, what is the most likely cause?