Unix timestamps in R
In R a POSIXct value is already Unix seconds with a timezone attribute for display. as.numeric reveals the number underneath.
Get the current Unix timestamp
as.numeric(Sys.time()) # seconds, with fraction
floor(as.numeric(Sys.time())) # whole seconds
round(as.numeric(Sys.time()) * 1000) # milliseconds
Convert a Unix timestamp to a date
as.POSIXct(1700000000, origin = "1970-01-01", tz = "UTC")
# [1] "2023-11-14 22:13:20 UTC"
as.POSIXct(1700000000123 / 1000, origin = "1970-01-01", tz = "UTC")
Since R 4.3.0 the origin argument can be left out for numbers.
Convert a date to a Unix timestamp
as.numeric(as.POSIXct("2026-11-14 10:00:00", tz = "UTC"))
# [1] 1794650400
as.numeric(as.POSIXct("2026-11-14 15:30:00", tz = "Asia/Kolkata"))
# [1] 1794650400
Timezones
x <- as.POSIXct(1700000000, tz = "UTC")
format(x, tz = "America/New_York", usetz = TRUE)
# [1] "2023-11-14 17:13:20 EST"
attr(x, "tzone") <- "Asia/Tokyo" # same instant, new display zone
Common mistakes
- Leaving out
tzuses the session zone for both parsing and printing. Passtz = "UTC"when reading UTC data. as.Date()on a POSIXct can use a different zone from the one you print in, so late-evening times may land on another day. Passtz =explicitly.- Data frames from CSV often hold timestamps as character. Convert with
as.POSIXct(as.numeric(col), tz = "UTC").
Complete example
now <- as.numeric(Sys.time())
cat("Now:", floor(now), "\n")
t <- as.POSIXct(1700000000, tz = "UTC")
cat("UTC:", format(t, "%Y-%m-%dT%H:%M:%SZ"), "\n")
cat("Back:", as.numeric(t), "\n")
Check any value with the epoch converter, or convert a whole column with the batch converter. All examples use 1700000000 (2023-11-14 22:13:20 UTC) and 1794650400 (2026-11-14 10:00:00 UTC).