There are two methods you can use to convert date values to numeric values in R:
Method 1: Use as.numeric()
as.numeric(my_date)
This will return the number of seconds that have passed between your date object and 1/1/1970.
Method 2: Use Functions from the lubridate package
library(lubridate) #get seconds value in date object second(my_date) #get minutes value in date object minute(my_date) ... #get year value in date object year(my_date)
This will return the value for the seconds, minutes, years, etc. from your date object.
The following examples show how to use each method in practice.
Method 1: Use as.numeric()
The following code shows how to convert a date object to numeric using the as.numeric() function:
#create date object
my_date POSIXct("10/14/2021 5:35:00 PM", format="%m/%d/%Y %H:%M:%S %p")
#view date object
my_date
[1] "2021-10-14 05:35:00 UTC"
#convert date object to number of seconds since 1/1/1970
as.numeric(my_date)
[1] 1634189700
#convert date object to number of days since 1/1/1970
as.numeric(my_date) / 86400
[1] 18914.23
#convert date object to number of years since 1/1/1970
as.numeric(my_date) / 86400 / 365
[1] 51.81982
Based on the output we can see:
- There is a difference of 1,634,189,700 seconds between our date object and 1/1/1970.
- There is a difference of 18,914.23 days between our date object and 1/1/1970.
- There is a difference of 51.81982 years between our date object and 1/1/1970.
Method 2: Use Functions from the lubridate Package
The following code shows how to convert a date object to numeric using functions from the lubridate package in R:
library(lubridate)
#create date object
my_date POSIXct("10/14/2021 5:35:00 PM", format="%m/%d/%Y %H:%M:%S %p")
#view date object
my_date
[1] "2021-10-14 05:35:00 UTC"
#extract various numerical values from date object
second(my_date)
[1] 0
minute(my_date)
[1] 35
hour(my_date)
[1] 5
day(my_date)
[1] 14
month(my_date)
[1] 10
year(my_date)
[1] 2021
Using these functions, we can extract the seconds, minutes, hours, days, months, and year values from our date object.
Refer to this online cheat sheet to gain a complete understanding of the most commonly used functions in the lubridate package.
Additional Resources
The following tutorials explain how to perform other common conversions in R:
How to Convert a String to Datetime in R
How to Convert Numbers to Dates in R
How to Sort a Data Frame by Date in R