Setting type date in R with format '05-Mar-2020 17:00:00'

I have a large amount of data with 18000 rows. One of the columns is a combined date and time. In the csv file the format is "05/03/2020 05:00:00 PM". When i read the csv into R it turns into a character with the format "05-Mar-2020 17:00:00". I need R to understand this column as the date and time.

I have tried the following and it just replaces the DateTimes with NAs.
‘dat’ is the dataframe and ‘DateTime’ is the column name.

dat[['DateTime']] <- as.POSIXct(dat[['DateTime']], format = "%d%-%m-%Y %H:%M:%S") 

>Solution :

x <- "05-Mar-2020 17:00:00"

as.POSIXct(x, format = "%d-%b-%Y %H:%M:%S")

# [1] "2020-03-05 17:00:00 CET"

use help(strptime) to see all format codes, you see that %b is used for the abbreviated month name instead of %m and that you had a redundant % sign as well.

Or you can use the lubridate package and do:

lubridate::dmy_hms(x)

Leave a Reply