Date & POSIXct
Objects in R
Learn to create and manipulate Date and POSIXct objects using as.Date() and as.POSIXct() for powerful time-based analysis in R.
R Programming
Why Dates Matter in R
When you read data into R, dates often arrive as plain character strings like "2024-03-15". R cannot do math on strings: it does not know that March 15 is one day after March 14. Date objects fix this by encoding dates as numbers R can compute with.
Two Core Classes: Date & POSIXct
Date
Stores calendar dates only (year, month, day). Internally, the number of days since 1970-01-01.
POSIXct
Stores date + time + time zone. Internally, the number of seconds since 1970-01-01 00:00:00 UTC.
Under the Hood: Numbers Behind Dates
Creating Dates with as.Date()
# Default format: YYYY-MM-DD (ISO 8601)
as.Date("2024-03-15")
[1] "2024-03-15"
# Custom format with format argument
as.Date("03/15/2024", format = "%m/%d/%Y")
[1] "2024-03-15"
# European style: day-month-year
as.Date("15-Mar-2024", format = "%d-%b-%Y")
[1] "2024-03-15"
Key Format Codes
| Code | Meaning | Example |
|---|---|---|
| %Y | 4-digit year | 2024 |
| %y | 2-digit year | 24 |
| %m | Month (01-12) | 03 |
| %b | Abbreviated month | Mar |
| %d | Day (01-31) | 15 |
| %H | Hour (00-23) | 14 |
| %M | Minute (00-59) | 30 |
| %S | Second (00-59) | 45 |
Creating Date-Times with as.POSIXct()
# Default: date + time in ISO format
as.POSIXct("2024-03-15 14:30:00")
[1] "2024-03-15 14:30:00 EDT"
# Specify a time zone
as.POSIXct("2024-03-15 14:30:00",
tz = "America/New_York")
# Custom format string
as.POSIXct("03/15/2024 2:30 PM",
format = "%m/%d/%Y %I:%M %p")
Date vs POSIXct: When to Use Which
| Feature | Date | POSIXct |
|---|---|---|
| Stores time? | ✕ No | ✓ Yes |
| Time zone? | ✕ No | ✓ Yes |
| Internal unit | Days | Seconds |
| Memory | Lighter | Heavier |
| Best for | Birthdays, calendar dates | Log timestamps, events |
Step-by-Step: Parsing a Date String
1
Inspect your raw string. What does it look like? e.g., "03/15/2024 14:30"
2
Choose the right function. Need time? Use as.POSIXct(). Date only? Use as.Date().
3
Build the format string. Match each piece: %m for month, / for slash, %d for day, etc.
4
Set tz for POSIXct. Always specify the time zone explicitly to avoid surprises.
5
Verify with class() and str(). Confirm the result is "Date" or "POSIXct", not "character".
Example 1: Basic Date Parsing
# Raw data: "March 15, 2024"
birthday <- as.Date("March 15, 2024",
format = "%B %d, %Y")
birthday
[1] "2024-03-15"
# Check the class
class(birthday)
[1] "Date"
# Underlying number
as.numeric(birthday)
[1] 19797
Example 2: Date Arithmetic
# Create two dates
start <- as.Date("2024-01-01")
end <- as.Date("2024-03-15")
# Subtract to find the difference
end - start
Time difference of 74 days
# Add 30 days to a date
start + 30
[1] "2024-01-31"
# Use difftime() for explicit units
difftime(end, start, units = "weeks")
Time difference of 10.57143 weeks
Example 3: POSIXct with Time Zones
# Parse a timestamp with time zone
event <- as.POSIXct("2024-03-15 09:00:00",
tz = "America/New_York")
event
[1] "2024-03-15 09:00:00 EDT"
# Display in another time zone (returns a string)
format(event, tz = "America/Los_Angeles", usetz = TRUE)
[1] "2024-03-15 06:00:00 PDT"
# Seconds since epoch
as.numeric(event)
[1] 1710507600
Getting Today's Date and Time
# Current date (Date class)
Sys.Date()
[1] "2024-03-15"
# Current date-time (POSIXct class)
Sys.time()
[1] "2024-03-15 14:30:22 EDT"
# Check classes
class(Sys.Date())
[1] "Date"
class(Sys.time())
[1] "POSIXct" "POSIXt"
Extracting Components from Dates
d <- as.Date("2024-03-15")
format(d, "%Y") # Year
[1] "2024"
format(d, "%m") # Month number
[1] "03"
format(d, "%B") # Full month name
[1] "March"
format(d, "%A") # Day of the week
[1] "Friday"
weekdays(d) # Also returns day name
[1] "Friday"
Common Mistakes to Avoid
✕ Wrong Format String
Using %m/%d/%y when the string is "15/03/2024" (day-first). Returns NA or the wrong date silently.
✕ Forgetting tz
Omitting tz in as.POSIXct() uses your local zone. Code breaks when a classmate in a different zone runs it.
✕ %Y vs %y
Using %y for a 4-digit year like "2024" can cause errors. For example, as.Date("01/01/2024", format="%d/%m/%y") incorrectly returns the year 2020.
Summary: Your Date Toolkit
| Task | Function | Returns |
|---|---|---|
| Parse date string | as.Date() | Date object |
| Parse date-time string | as.POSIXct() | POSIXct object |
| Get today's date | Sys.Date() | Date object |
| Get current time | Sys.time() | POSIXct object |
| Format for display | format() | Character string |
| Date difference | difftime() | difftime object |
| Get underlying number | as.numeric() | Numeric |
Question 1 of 5
What does R's Date class store internally?
The Date class stores an integer counting days since January 1, 1970 (the epoch). Seconds since the epoch is how POSIXct works, not Date.
Question 2 of 5
Which code correctly parses "15/03/2024" (day/month/year) into a Date?
The string starts with day (15), then month (03), then 4-digit year (2024). That matches %d/%m/%Y. Option B swaps day and month. Option D uses lowercase %y, which expects a 2-digit year.
Question 3 of 5
What is the key difference between Date and POSIXct?
Date stores only year-month-day information with no time component. POSIXct stores the full date, time (hours, minutes, seconds), and time zone. Both are stored as numbers internally, not characters.
Question 4 of 5
If you run as.Date("2024-01-10") + 7, what is the result?
Adding a number to a Date adds that many days. January 10 + 7 days = January 17. Date arithmetic works because dates are stored as numbers internally.
Question 5 of 5
Why is it important to specify tz when using as.POSIXct()?
R does not throw an error when tz is missing: it silently uses your system's local time zone. This means the same code can produce different results on different computers, creating hard-to-find bugs.