Reading — step 1 of 4
Learn
~1 min readReal-World Data Workflow
R has three main time types:
- Date — calendar date, no time.
as.Date("2026-05-08") - POSIXct — timestamp with timezone. Stored as seconds since 1970.
- POSIXlt — broken-down time (year, month, day, ...). List-like.
Parsing:
as.Date("2026-05-08") # ISO format default
as.Date("05/08/2026", format = "%m/%d/%Y")
as.POSIXct("2026-05-08 14:30:00", tz = "UTC")
Format codes (mostly strftime-compatible):
%Y4-digit year,%y2-digit%mmonth,%dday,%Hhour (24h),%I(12h),%pAM/PM%Mminute,%Ssecond%ashort weekday,%Afull weekday%bshort month,%Bfull month
Formatting back to string:
format(Sys.Date(), "%Y-%m-%d") # ISO
format(Sys.time(), "%A, %B %d at %I:%M %p")
Arithmetic — adding/subtracting durations:
as.Date("2026-05-08") + 7 # one week later
Sys.Date() - as.Date("2020-01-01") # difftime in days
library(lubridate)
ymd("2026-05-08") + days(30)
ymd("2026-05-08") + months(3) # lubridate handles month math correctly
Sys.Date() and Sys.time() for now:
Sys.Date() # "2026-05-08"
Sys.time() # "2026-05-08 14:32:01 UTC"
Components with POSIXlt:
t <- as.POSIXlt(Sys.time())
t$year + 1900 # year (POSIXlt stores year - 1900!)
t$mon + 1 # month (0-indexed!)
t$mday # day of month
t$wday # day of week (0 = Sunday)
The 1900 / 0-indexing legacy is a famous footgun.
lubridate (tidyverse) is the modern way:
library(lubridate)
ymd("2026-05-08") # parse year-month-day
mdy("05/08/2026") # month-day-year
dmy("08-05-2026") # day-month-year
ymd_hms("2026-05-08 14:30:00") # with time
year(today()) # 2026
month(today()) # 5
wday(today(), label = TRUE) # "Fri" (or whatever)
today() %within% interval(ymd("2026-01-01"), ymd("2026-12-31")) # TRUE
Time series with xts and zoo packages — for financial data, sensors, anything with a regular time index.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…