如何检查字符串是否为 R 中的日期时间格式?
How to check if a string is in datetime format in R?
编辑:是否可以检查字符串是否为特定格式,例如 'y-m-d'、'h:m:s'
lubridate::is.timepoint(Sys.time())
#> TRUE
lubridate::is.timepoint(Sys.Date())
#> TRUE
来自 ?lubridate::is.timepoint
的文档:
TRUE if x is a POSIXct, POSIXlt, or Date object, FALSE otherwise.
如果您只想识别日期时间而不是日期:
lubridate::is.POSIXt(Sys.time())
#> TRUE
lubridate::is.POSIXt(Sys.Date())
#> FALSE
编辑。
如果你想检查一个特定的格式,你可以尝试用那个格式读取它,如果你得到 NA,那么它就不是。
例如:
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
没有润滑:
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")
#> TRUE
但是,lubridate 为您提供了更大的灵活性。喜欢:
is.ymd_hms("2020/01/01 22:22:22")
#> TRUE
is.ymd_hms2("2020/01/01 22:22:22")
#> FALSE
编辑:是否可以检查字符串是否为特定格式,例如 'y-m-d'、'h:m:s'
lubridate::is.timepoint(Sys.time())
#> TRUE
lubridate::is.timepoint(Sys.Date())
#> TRUE
来自 ?lubridate::is.timepoint
的文档:
TRUE if x is a POSIXct, POSIXlt, or Date object, FALSE otherwise.
如果您只想识别日期时间而不是日期:
lubridate::is.POSIXt(Sys.time())
#> TRUE
lubridate::is.POSIXt(Sys.Date())
#> FALSE
编辑。
如果你想检查一个特定的格式,你可以尝试用那个格式读取它,如果你得到 NA,那么它就不是。
例如:
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
没有润滑:
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")
#> TRUE
但是,lubridate 为您提供了更大的灵活性。喜欢:
is.ymd_hms("2020/01/01 22:22:22")
#> TRUE
is.ymd_hms2("2020/01/01 22:22:22")
#> FALSE