Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 39 ยท Strings, Dates and Regular Expressions

Dates and Times in R: Date, POSIXct, format and difftime

Work with dates and times in base R: as.Date, format codes, date arithmetic, seq, difftime, POSIXct and POSIXlt, time zones, and the traps of month-end dates.

Dates look simple until you need to subtract them, sort them, group them by month or compare two time zones. R has proper date and time classes so that you do not have to do arithmetic on text. This lesson covers the classes in base R: Date for calendar days, and POSIXct / POSIXlt for moments in time. The tidyverse package lubridate (next lesson) makes the same jobs shorter, but it is built on these ideas.

The Date class

A Date is stored as the number of days since 1970-01-01 (the Unix epoch), and printed as YYYY-MM-DD. Create one with as.Date():

R
d <- as.Date("2026-03-15")
class(d)                # "Date"
as.numeric(d)           # 20527  (days since 1970-01-01)
d + 30                  # "2026-04-14"

Because it is a number underneath, adding days, comparing dates and sorting just work: d + 30 is 30 days later, d > as.Date("2026-01-01") is TRUE, and sort() orders dates chronologically (text would sort them alphabetically, which is only correct for ISO format).

If your text is not in YYYY-MM-DD form, tell as.Date() the layout with a format string:

R
as.Date("15/03/2026", format = "%d/%m/%Y")     # "2026-03-15"
as.Date("03/15/26",   format = "%m/%d/%y")     # "2026-03-15"
as.Date("2026-02-30", format = "%Y-%m-%d")     # NA  (there is no Feb 30)

An impossible date gives NA rather than an error, which is useful when cleaning data: count them with sum(is.na(parsed)) and look at the originals that failed.

Format codes

The same codes work for reading (as.Date(format=)) and writing (format()).

Code Meaning Example for 2026-03-15
%Y 4-digit year 2026
%y 2-digit year 26
%m month number 03
%B / %b month name / abbreviation March / Mar
%d day of month 15
%A / %a weekday name / abbreviation Sunday / Sun
%j day of year 074
%H %M %S hour (24 h), minute, second 14 30 00
R
d <- as.Date("2026-03-15")
format(d, "%A, %d %B %Y")      # "Sunday, 15 March 2026"
format(d, "%b %Y")             # "Mar 2026"
weekdays(d)                    # "Sunday"
months(d)                      # "March"
format(d, "%j")                # "074"

Weekday and month names follow the computer's locale, so the output may be in another language on a non-English system.

Date arithmetic

Subtracting two dates gives a difftime object, which knows its unit:

R
d1 <- as.Date("2026-03-15")
d2 <- as.Date("2026-12-25")
d2 - d1                                   # Time difference of 285 days
as.numeric(d2 - d1)                       # 285
difftime(d2, d1, units = "weeks")         # Time difference of 40.71429 weeks
as.Date("2028-03-01") - as.Date("2028-02-01")   # Time difference of 29 days (leap year)

diff() on a vector of dates gives the gaps between neighbors:

R
diff(as.Date(c("2026-01-01", "2026-01-15", "2026-02-01")))
# Time differences in days
# [1] 14 17

seq() builds sequences of dates by day, week, month, quarter or year:

R
seq(d1, by = "month", length.out = 3)     # "2026-03-15" "2026-04-15" "2026-05-15"
seq(d1, as.Date("2026-04-05"), by = "week")   # "2026-03-15" "2026-03-22" "2026-03-29" "2026-04-05"

Month-end trap. Base R's seq(by = "month") just adds one to the month number and lets the calendar roll over. Starting from January 31, February 31 does not exist and becomes March 3: seq(as.Date("2026-01-31"), by = "month", length.out = 3) gives "2026-01-31" "2026-03-03" "2026-03-31". If you mean "the last day of each month", build it from the first day of the next month minus one day.

Pulling out the parts

format() returns text; for numbers use POSIXlt, a list-like class that exposes the components:

R
lt <- as.POSIXlt(as.Date("2026-03-15"))
lt$year + 1900    # 2026  (years since 1900)
lt$mon + 1        # 3     (months are 0-11)
lt$mday           # 15
lt$wday           # 0     (0 = Sunday)
lt$yday           # 73    (0-based day of year)

The offsets (+ 1900, + 1) are a classic source of off-by-one bugs; they are the main reason people prefer lubridate::year().

Date-times: POSIXct and POSIXlt

A moment in time with a clock needs POSIXct, the number of seconds since 1970-01-01 00:00 UTC:

R
t <- as.POSIXct("2026-03-15 14:30:00", tz = "UTC")
t + 3600                                   # "2026-03-15 15:30:00 UTC"
format(t, "%H:%M")                         # "14:30"
as.numeric(t)                              # 1773585000

t2 <- as.POSIXct("2026-03-15 18:00:00", tz = "UTC")
t2 - t                                     # Time difference of 3.5 hours
difftime(t2, t, units = "mins")            # Time difference of 210 mins

Adding a number to a POSIXct adds seconds (to a Date it adds days). That difference between the two classes is a frequent mistake.

Time zones

A POSIXct is an absolute moment; the time zone only changes how it is displayed:

R
format(t, tz = "America/New_York", usetz = TRUE)   # "2026-03-15 10:30:00 EDT"
format(t, tz = "Asia/Tokyo",       usetz = TRUE)   # "2026-03-15 23:30:00 JST"

Always pass tz explicitly when you parse. Without it R silently uses the computer's own zone, so the same script gives different instants on different machines. Store and exchange times in UTC, and convert to local zones only for display. Sys.Date() and Sys.time() return today and now; their values naturally change on every run.

Working with dates in a data frame

R
sales <- data.frame(
  day    = as.Date(c("2026-01-05", "2026-01-20", "2026-02-03", "2026-02-11")),
  amount = c(100, 150, 80, 120)
)
sales$month <- format(sales$day, "%Y-%m")
aggregate(amount ~ month, data = sales, FUN = sum)
#     month amount
# 1 2026-01    250
# 2 2026-02    200

Grouping by a formatted "%Y-%m" string is the simplest way to total by month. The result sorts correctly because the year comes first. Use cut(sales$day, "month") for a version that keeps the groups as factor levels.

Compare with Python

Python's datetime module follows the same model. This block is a comparison you can run, not R.

Python Python comparison: dates and times

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common mistakes

  • Keeping dates as character columns. Convert them right after reading the file.
  • Parsing ambiguous strings such as 03/04/2026 without a format. Is it March 4 or April 3? Always state the format.
  • Forgetting that Date + n adds days but POSIXct + n adds seconds.
  • Leaving out tz, so that results depend on the computer.
  • Doing month arithmetic by adding 30 days. Use seq(by = "month") and mind the month-end rule.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What number does as.numeric() give for a Date object?

    A Date counts days from the Unix epoch, 1970-01-01. A POSIXct counts seconds instead.
  2. 2. Which call correctly parses "15/03/2026"?

    The format string must describe the layout: day, month, four-digit year, separated by slashes.
  3. 3. What does t + 3600 do when t is a POSIXct?

    POSIXct is measured in seconds, so adding 3600 moves the time forward one hour.
  4. 4. What does as.POSIXlt(d)$mon return for a date in March?

    POSIXlt months run from 0 to 11, so March is 2. Add 1 to get the usual month number.

Summary

  • Date counts days since 1970-01-01; POSIXct counts seconds since 1970-01-01 UTC.
  • Parse and print with format codes such as %Y-%m-%d, %B, %A, %H:%M.
  • Subtracting dates gives a difftime; use difftime(units = ...) to choose the unit.
  • seq(by = "month") rolls over at month ends; always set tz for date-times.
  • POSIXlt exposes the parts, with offsets (year from 1900, months from 0).

Next: stringr and lubridate