'How to change datetime to just date in a new column in R Programming? [duplicate]

I am very new to R but trying my best to learn! Need help adding a column for just the date, parsed from datetime data.

My data looks like this:

city | state | datetime
Sand | CA.   | 2017-12-22 14:07:00

I would like to add a fourth column with just the date. I thought I could use Lubridate but the function ymd_hms("datetime") will not parse the data.

Thank you for your help



Solution 1:[1]

You can just use as.Date to pull out the date from the date and time.

library(dplyr)

df %>% 
  mutate(date = as.Date(datetime))

Or if your date time column is just a character, then you need to convert to POSIXct first.

df %>% 
  mutate(date = as.Date(as.POSIXct(datetime)))

Or in base R:

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

Output

  city state            datetime       date
1 Sand   CA. 2017-12-22 14:07:00 2017-12-22

Data

df <- structure(list(city = "Sand", state = "CA.", datetime = structure(1513980420, class = c("POSIXct", 
"POSIXt"), tzone = "")), class = "data.frame", row.names = c(NA, 
-1L))

Solution 2:[2]

if you have store the data in dataframe named data then below is code to add a new column of date in your dataframe.

data$date = as.Date(data$datetime)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 marc_s