Search code examples
rdata-manipulationlubridate

How to convert a string into a date-time object


The data is character and I want it to be date-time. I have the cheat sheet with me but there isn't any format that I can use that satisfies the weird date format. Any suggestions?

x <- 'Fri Dec 11 12:10:51 PST 2020'

Solution

  • You can use the anytime package

    > library(anytime)
    > anytime("Fri Dec 11 12:10:51 PST 2020")
    [1] "2020-12-11 12:10:51 CST"
    > 
    > class(anytime("Fri Dec 11 12:10:51 PST 2020"))
    [1] "POSIXct" "POSIXt" 
    > 
    

    It has three key advantages:

    • it can guess the format (as here)
    • it converts all sorts of input format (incl character, factor, ...)
    • it is pretty fast (as the parser is C++ from Boost)

    It is pretty standard for most methods to ignore the timezone attribute. So the PST became my local time, i.e. Central.