How to Parse Date in R: Syntax, Examples, and Tips
In R, you can parse dates using the
as.Date() function for simple date formats or strptime() for more complex date-time strings. Specify the format using format codes like %Y for year, %m for month, and %d for day to correctly convert strings to date objects.Syntax
The main functions to parse dates in R are as.Date() and strptime(). Use as.Date(x, format) to convert a character string x to a Date object by specifying the date format. Use strptime(x, format) to parse date-time strings into POSIXlt objects, which include time components.
Common format codes include:
%Y: 4-digit year (e.g., 2024)%m: 2-digit month (01-12)%d: 2-digit day (01-31)%H: hour (00-23)%M: minute (00-59)%S: second (00-59)
r
as.Date(x, format = "%Y-%m-%d") strptime(x, format = "%Y-%m-%d %H:%M:%S")
Example
This example shows how to parse a simple date string and a date-time string in R. It demonstrates converting strings to Date and POSIXlt objects.
r
date_string <- "2024-06-15" datetime_string <- "2024-06-15 14:30:00" # Parse date only parsed_date <- as.Date(date_string, format = "%Y-%m-%d") # Parse date and time parsed_datetime <- strptime(datetime_string, format = "%Y-%m-%d %H:%M:%S") parsed_date parsed_datetime
Output
[1] "2024-06-15"
[1] "2024-06-15 14:30:00"
Common Pitfalls
Common mistakes when parsing dates in R include:
- Not matching the format string exactly to the input date format.
- Using
as.Date()for date-time strings without time, which drops the time part. - Ignoring locale settings that affect month or day names.
Always check your format codes carefully and use strptime() if you need to keep time information.
r
wrong_date <- "15/06/2024" # Wrong: format does not match input as.Date(wrong_date, format = "%Y-%m-%d") # returns NA # Correct format as.Date(wrong_date, format = "%d/%m/%Y") # returns "2024-06-15"
Output
[1] NA
[1] "2024-06-15"
Quick Reference
| Format Code | Meaning | Example |
|---|---|---|
| %Y | 4-digit year | 2024 |
| %y | 2-digit year | 24 |
| %m | 2-digit month | 06 |
| %d | 2-digit day | 15 |
| %H | Hour (24-hour) | 14 |
| %M | Minute | 30 |
| %S | Second | 00 |
Key Takeaways
Use as.Date() with the correct format string to parse simple date strings.
Use strptime() to parse date-time strings when time information is needed.
Match the format string exactly to your input date format to avoid parsing errors.
Check your locale if parsing month or day names in text form.
Always test your parsing code with sample inputs to ensure correct conversion.