Here are two ways to convert Date to Numeric in R:
- Using the as.numeric() function
- Using the lubridate package
Method 1: Using as.numeric() function
Before using the “as.numeric()” function, you must create a date object using the “as.POSIXct()” function and then convert the date to numeric.
Syntax
as.numeric(date)
Parameters
date: It is a date object that needs to be converted to numeric.
Example
today_date <- as.POSIXct("2023-02-24 13:09:00", tz = "GMT")
as.numeric(today_date)
Output
[1] 1677244140
Applying an as.numeric() function to a POSIXct object will return the number of seconds since January 1, 1970 (the Unix epoch) at the specified date and time.
However, you need to know the time zone used in your POSIXct object to get the correct result.
Method 2: Using a lubridate package
To use the lubridate package, you must “install and load” the lubridate package using install.packages(“lubridate”).
After that, you must import the package using the library(lubridate) function at the top of the file.
Then, you can use different functions from the package to extract different time units from your date object.
Syntax
library(lubridate)
#get year value in date object
year(date)
#get seconds value in date object
second(date)
#get minutes value in date object
minute(date)
Example
library(lubridate)
today_date <- as.POSIXct("2023-02-24 13:09:00", tz = "GMT")
hour(today_date)
minute(today_date)
second(today_date)
day(today_date)
month(today_date)
year(today_date)
Output
[1] 13
[1] 9
[1] 0
[1] 24
[1] 2
[1] 2023
That’s it!

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.