Extracting time from character string with strptime() in R, returning NA

ぃ、小莉子 提交于 2019-11-30 19:35:35

R doesn't know that your string is a datetime. So make it one first:

y <- strptime(x, format='%m/%d/%Y %H:%M')

If you were trying to get just the date, you could do:

strptime(x, '%m/%d/%Y') 

Because strptime discards any extra characters past your format string, but you cannot grab the trailing %H:%M because the function doesn't know where to start.

Once it is a proper datetime class, you can do things to it:

strftime(y, '%H:%M')

I prefer to use as.POSIXlt rather than strptime and format instead of strftime... but they are roughly equivalent.

If your goal is to obtain a string with the time, you can use regular expressions in sub. If you use strptime on a string with no date information, today's date is used.

x <- "2/7/2013 7:43"

x2 <- sub(".* ", "", x)
# [1] "7:43"

strptime(x2, "%R")
# [1] "2014-02-05 07:43:00"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!