TechBuzzPro

Dates and Times in R: A Practical Guide

· 6 min read · Apps & Browsers

In this article
  1. Background: Why R Needs Special Date/Time Classes
  2. How It Works: Core Functions and Classes
  3. Formatting and Parsing: The Format Codes
  4. Arithmetic and Comparisons
  5. Time Zones and Daylight Saving Time
  6. Using the lubridate Package
  7. Parse "March 15, 2024"
  8. Extract month
  9. Add 2 months
  10. Common Problems and Solutions
  11. Frequently Asked Questions

Dates and times in R are handled through specialized classes—Date, POSIXct, and POSIXlt—that store calendar dates and clock times as numeric values or lists, allowing for arithmetic, formatting, and time-zone-aware operations. This guide explains the core concepts, shows how to parse, manipulate, and format dates and times, and covers common pitfalls like time zones and daylight saving time.

Background: Why R Needs Special Date/Time Classes

In base R, a plain number can represent a date if you remember what it means, but that approach breaks down quickly. For example, adding 1 to a number representing January 1, 2024 might give January 2, but what about adding 1 to a number representing 11:30 PM? Does it become 12:30 AM the same day or the next day? R's date/time classes solve this by embedding rules for days, months, leap years, and time zones into the data structure itself.

The three main classes are:

  • Date: stores a calendar date (year, month, day) as the number of days since 1970-01-01. Internally it's an integer or double, but it prints as a date.
  • POSIXct: stores a date and time as the number of seconds since 1970-01-01 00:00:00 UTC. It's a compact, numeric representation that is easy to store in data frames.
  • POSIXlt: stores a date and time as a list of components (year, month, day, hour, minute, second, etc.). It's more human-readable but takes more memory and is slower for computations.

Most modern R work uses Date for dates and POSIXct for date-times, especially in data frames and with packages like lubridate and dplyr.

How It Works: Core Functions and Classes

Here are the essential functions you'll use daily:

  • Sys.Date() returns today's date as a Date object.
  • Sys.time() returns the current date-time as a POSIXct object.
  • as.Date(x, format) converts a character string or numeric vector to a Date.
  • as.POSIXct(x, format, tz) converts to POSIXct.
  • format(x, format) converts a date/time object to a character string in a specified format.
  • strptime(x, format, tz) converts a character string to POSIXlt (but you can wrap it in as.POSIXct()).

For example, to parse a date string:

d <- as.Date("2024-03-15")       # ISO standard, no format needed
print(d)                        # "2024-03-15"
class(d)                        # "Date"

For a date-time with a custom format:

dt <- as.POSIXct("15/03/2024 14:30", format = "%d/%m/%Y %H:%M", tz = "UTC")
print(dt)                       # "2024-03-15 14:30:00 UTC"

Formatting and Parsing: The Format Codes

Both as.Date() and format() rely on format strings that use percent-prefixed codes. The most common ones:

  • %Y – 4-digit year (e.g., 2024)
  • %y – 2-digit year (e.g., 24)
  • %m – month as a number (01-12)
  • %b – abbreviated month name (Jan, Feb)
  • %B – full month name (January)
  • %d – day of the month (01-31)
  • %H – hour (00-23)
  • %M – minute (00-59)
  • %S – second (00-59)
  • %A – full weekday name (Monday)
  • %a – abbreviated weekday (Mon)
  • %j – day of the year (001-366)
  • %Z – time zone abbreviation (UTC)

When parsing, the format must exactly match the string. For example, "2024-03-15" uses "%Y-%m-%d", while "15 Mar 2024" uses "%d %b %Y".

A common mistake is forgetting that %m expects a zero-padded number. If your data has "3" instead of "03", you need to preprocess or use %m with a non-padded version (which R doesn't support directly; you'd need to pad the string).

Arithmetic and Comparisons

You can do math with dates and times, which is one of the main reasons to use these classes:

  • date1 - date2 gives a difftime object, which prints as days, hours, etc.
  • date + number adds days to a Date object; for POSIXct, it adds seconds.
  • You can compare dates with <, >, ==, etc.

Example:

d1 <- as.Date("2024-01-01")
d2 <- as.Date("2024-01-10")
d2 - d1   # Time difference of 9 days

dt <- as.POSIXct("2024-01-01 12:00:00", tz = "UTC")
dt + 3600  # adds 1 hour (3600 seconds)

When you subtract two POSIXct objects, the result is in seconds by default, but you can change the units with difftime() or by setting units in the difftime object.

Time Zones and Daylight Saving Time

Time zones are the most confusing part of working with dates and times. R stores POSIXct as seconds since epoch in UTC, but it displays the time in the time zone specified by the tz attribute. If you don't specify a time zone, R uses your system's local time zone.

Key points:

  • Always specify tz when parsing or creating date-times to avoid ambiguity.
  • Use OlsonNames() to see valid time zone names (e.g., "America/New_York", "Europe/London", "UTC").
  • Daylight saving time (DST) can cause hours to be skipped or repeated. R handles this correctly if you use the correct time zone.
  • When comparing times across zones, convert all to UTC first.

Example of DST issue:

# In America/New_York, DST starts on 2024-03-10 at 2 AM
as.POSIXct("2024-03-10 02:30:00", tz = "America/New_York")  # NA, because 2:30 AM doesn't exist

To avoid such problems, consider using lubridate's force_tz() or with_tz() for explicit control.

Using the lubridate Package

While base R is sufficient, the lubridate package (part of the tidyverse) simplifies many operations. It provides intuitive functions like ymd(), mdy(), dmy() for parsing, and year(), month(), day() for extracting components. It also handles time zones more gracefully.

Example:

library(lubridate)

Parse "March 15, 2024"

d <- mdy("March 15, 2024")

Extract month

month(d) # 3

Add 2 months

d + months(2) # "2024-05-15"

Lubridate also has interval(), duration(), and period() classes for different types of time arithmetic, which can be more intuitive than base R.

Common Problems and Solutions

  • Parsing fails because of wrong format: Always check the exact string format. Use strptime with a known format to test.
  • Time zone mismatch: If you see times off by hours, check the tz attribute. Use attr(x, "tzone") to inspect.
  • NA values after parsing: Often due to invalid dates (e.g., Feb 30) or times that don't exist due to DST. Use na.rm or filter invalid entries.
  • Date-time as character in data frame: Convert with as.POSIXct() or lubridate::ymd_hms().
  • Daylight saving time causing duplicate or missing hours: Use force_tz() to set the time zone without changing the clock time, or use UTC for storage.

Frequently Asked Questions

How do I get today's date in R?

Use Sys.Date() to get the current date as a Date object. If you need the current date and time, use Sys.time() which returns a POSIXct object.

How do I convert a character string to a date in R?

Use as.Date() with the appropriate format. For example, as.Date("2024-03-15") works for ISO format, but for "15/03/2024" you need as.Date("15/03/2024", format = "%d/%m/%Y").

How do I extract the year, month, or day from a date?

Use format() with format codes: format(d, "%Y") for year, "%m" for month, "%d" for day. Alternatively, use lubridate::year(d), month(d), day(d).

Why does my date-time show the wrong time zone?

By default, R uses your system's time zone. If you want a specific zone, specify tz when parsing or creating the object. Use attr(x, "tzone") to check the current time zone.

How do I calculate the difference between two dates in days?

Subtract one Date object from another. The result is a difftime object, which prints in days. You can convert to numeric with as.numeric(diff, units = "days").

What is the difference between POSIXct and POSIXlt?

POSIXct stores time as seconds since 1970-01-01 UTC (a numeric vector), which is compact and easy to compute with. POSIXlt stores time as a list of components (year, month, day, hour, etc.), which is more readable but slower and memory-intensive. In practice, you'll mostly use POSIXct.