Search code examples
rtidyverselubridate

How to check if a string is in datetime format in R?


Edit: Is it possible to check if the string is in a certain format such as 'y-m-d','h:m:s'


Solution

  • lubridate::is.timepoint(Sys.time())
    #> TRUE
    lubridate::is.timepoint(Sys.Date())
    #> TRUE
    

    From the documentation of ?lubridate::is.timepoint:

    TRUE if x is a POSIXct, POSIXlt, or Date object, FALSE otherwise.


    If you want to identify only datetimes and not dates:

    lubridate::is.POSIXt(Sys.time())
    #> TRUE
    lubridate::is.POSIXt(Sys.Date())
    #> FALSE
    

    EDIT.

    If you want to check a specific format you can try to read it with that format, if you get NA, then it is not.

    For example:

    is.ymd_hms <- function(x) !is.na(lubridate::ymd_hms(x, quiet = TRUE))
    
    is.ymd_hms("2020-01-01 22:22:22")
    #> TRUE
    is.ymd_hms("2020-31-01 22:22:22")
    #> FALSE
    

    Without lubridate:

    is.ymd_hms2 <- function(x) !is.na(as.Date(x, "%Y-%m-%d %H:%M:%S"))
    
    is.ymd_hms2("2020-01-01 22:22:22")
    #> TRUE
    is.ymd_hms2("2020-31-01 22:22:22")
    #> FALSE
    

    However, lubridate gives you more flexibility. Like:

    is.ymd_hms("2020/01/01 22:22:22")
    #> TRUE
    is.ymd_hms2("2020/01/01 22:22:22")
    #> FALSE