How to Extract Year, Month, Day and Other Parts from a Date in R

04.29.2021

Once you have a date object, it is often helpful to extract the year, month and other parts from it. In this article, we will learn how to extract parts of a date in R.

To extract parts of a date in R, we first need to convert our date to a POSIXlt object. Then, we can use the property access operator $ to extract the parts. Here is a list of many parts you can abstract.

date = as.Date("2021-04-25")
pos.date = as.POSIXlt(date)

pos.date$mday # day of the month

pos.date$mon # month

pos.date$year + 1900 # year since 1900 (so we add 1900 to get the current year)

pos.date$isdst # Is daylight savings

pos.date$yday # day of the year (0-365)

pos.date$wday # day of the week (0-6, 0 = Sun)

pos.date$hour
pos.date$min
pos.date$sec