Search code examples
rlubridate

In R, take a date string and convert it to datetime format (using lubridate)


In R I am trying to take a date string and convert it to date time format using lubridate but anm getting an error that:

All formats failed to parse. No formats found. 

Using this code:

lubridate::as_date("1/2/34")

Shouldn't this just return a formated date time?


Solution

  • as.Date or as_Date needs format. By default, it can parse if the format is %Y-%m-%d. Here, it is not the case. So

    lubridate::as_date("1/2/34", format ="%d/%m/%y")
    

    Or more compactly

    lubridate::dmy("1/2/34")
    

    Based on the string, it is not clear whether it is day/month/year or month/day/year. Also, for 2-digit year, there is an issue with prefix i.e. it can be either "19" or "20". Here, it would parse at "2034"