how to convert a dataframe column to datetime

hello, im a beginner in r. I have a huge csv file so i need to use rstudio to edit it. i want to convert 2 columns(which are in characters) into datetime format. can somebody please guide me?

My favorite package for working with dates is 'lubridate'. I don't know how new you are so I'll just write what I would have liked to know when I started with R. Code below:

To install lubridate onto your machine so you can work with it, run:

install.packages('lubridate')
library(lubridate)

There are several functions to coerce a vector of character dates to datetime format.
If your dates look like this '2019-04-04', use the function 'ymd()'.

ymd('2019-04-04') 

If your dates are in the format of month-day-year, use 'mdy()', etc.

Here's the 'lubridate' cheat sheet that offers an overview of its date functions:

thanks for responding. ill try to elaborate. so i read a large csv file into a df. now this df has 2 columns which are dates(mdy_hms) but it s recognized as characters. now i want to convert these two columns and then save my csv file again. i have the lubridate cheat sheet but i couldnt find how to apply lubridate to specific columns.

Oh, if you want to use base R for converting the columns, maybe try:

df$your_column_name <- mdy_hms(df$your_column_name)

This takes your column, changes to datetime format, and puts it back in 'df'.
There are much more elegant ways of doing it. 'dplyr' is really useful for working with dataframes.

You can save a new csv with something like:

library(readr)
write_csv(x = df, file = "/home/new.csv"))

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.