How do you convert datetime to date in R?

In R, the as.Date() function can be used to convert a datetime object to a date object. The as.Date() function takes a character string or numeric value that represents a date, and returns an R Date object. The function also accepts an input format, which can be used to convert other types of date objects into a Date object. For example, as.Date(as.POSIXct(x)) can be used to convert a POSIXct object into a Date object.


You can use the as.Date() function to convert a datetime to a date in R.

This function uses the following basic syntax:

df$date <- as.Date(df$datetime)

The following example shows how to use this syntax in practice.

Example: Convert Datetime to Date in R

Suppose we have the following data frame in R that contains information about sales made at some store:

#create data frame
df <- data.frame(dt=as.POSIXct(c('2023-01-01 10:14:00 AM', '2023-01-12 5:58 PM',
                                 '2023-02-23 4:13:22 AM', '2023-02-25 10:19:03 PM')),
                 sales = c(12, 15, 24, 31))

#view data frame
df

                   dt sales
1 2023-01-01 10:14:00    12
2 2023-01-12 05:58:00    15
3 2023-02-23 04:13:00    24
4 2023-02-25 10:19:00    31

The dt column contains the date and time of the sale.

We can use the class() function to view the class of this column:

#view class of dt column
class(df$dt)

[1] "POSIXct" "POSIXt" 

We can see that the dt column currently has a class of POSIXct, which is a datetime class.

To convert this column to a date, we can use the as.Date() function:

#convert dt column to date
df$dt <- as.Date(df$dt)

#view updated data frame
df

          dt sales
1 2023-01-01    12
2 2023-01-12    15
3 2023-02-23    24
4 2023-02-25    31

Notice that the time has been dropped from each datetime value in the dt column.

We can verify that the dt column now has a date class by using the class() function:

#view class of dt column
class(df$dt)

[1] "Date"

We can see that the dt column is indeed a date now.

The following tutorials explain how to perform other common operations in R:

x