Skip to content

POSIXct

Create

Action Code Details
From ymd
ISOdate(year, month, day)
From ymd
lubridate::make_date(year, month, day) |> as.POSIXct()
From ymdhms
ISOdatetime(year, month, day, hour, minute, second)
From ymdhms
lubridate::make_datetime(year, month, day, hour, min, sec)
From ymdhms in UTC timezone
ISOdatetime(years, months, days, hours, minutes, seconds, tz = 'UTC')
Current date in UTC
Sys.Date() |> as.POSIXct()
Current datetime
Sys.time()
Current datetime
lubridate::now()
Current datetime in UTC timezone
lubridate::now(tzone = 'UTC')
Unix epoch
as.POSIXct(0)
From total seconds since Unix epoch
as.POSIXct(n)
From total seconds since reference date
as.POSIXct(n, origin = ref_date)
Datetime from YYYY-MM-DD string
as.POSIXct(x)
Datetime from YYYY-MM-DD HH:mm:ss string
as.POSIXct(x)
Date from DD-MM-YYYY string
as.POSIXct(x, format = '%d-%m-%Y')

Test

Action Code Details
Is POSIXt
inherits(x, 'POSIXt')
Is POSIXt
lubridate::is.POSIXt(x)
Is POSIXct
inherits(x, 'POSIXct')
Is POSIXct
lubridate::is.POSIXct(x)
Same date
x == y
Happens before y
x < y
Happens after y
x > y

Extract

Action Code Details
Days from Unix epoch
as.Date(x) |> as.integer()
Seconds from Unix epoch (timestamp)
as.integer(x)
Year
lubridate::year(x)
Month
lubridate::month(x)
Day
lubridate::day(x)
Week number (1-53)
lubridate::week(x)
ISO week number (1-52)
lubridate::isoweek(x)
Weekday number
lubridate::wday(x, week_start = 1)
Mon=1, Sun=7
Hour
lubridate::hour(x)
Minute
lubridate::minute(x)
Second
lubridate::second(x)

Derive

Action Code Details
Shift forward by n days
x + n * 86400
Shift forward by n days
x + lubridate::days(n)
Shift forward by n seconds
x + n
Shift forward by a specific ymdhms period
x + lubridate::period(year, month, day, hour, minute, second)
Truncate to date
trunc(x, 'days') |> as.POSIXct()
Drops the time component, falling back to midnight 00:00:00
Truncate to hours
trunc(x, 'hours') |> as.POSIXct()
Truncate to minutes
trunc(x, 'mins') |> as.POSIXct()

Convert

Action Code Details
To Date
as.Date(x)
To POSIXlt
as.POSIXlt(x)

Format as string

Action Code Details
Format as ISO datetime (yyyy-mm-dd HH:MM:SS.SSS)
as.character(x)
Format as yyyy-mm-dd HH:MM:SS
format(x)
Format as yyyy-mm-dd
format(d, '%Y-%m-%d')
Format as dd-mm-yyyy
format(d, '%d-%m-%Y')
Format in system locale
format(x, '%a %b %d')