Parse timestamp with a.m./p.m

与世无争的帅哥 提交于 2020-01-12 14:31:55

问题


I have a file that formats time stamps like 25/03/2011 9:15:00 p.m.

How can I parse this text to a Date-Time class with either strptime or as.POSIXct?

Here is what almost works:

> as.POSIXct("25/03/2011 9:15:00", format="%d/%m/%Y %I:%M:%S", tz="UTC")
[1] "2011-03-25 09:15:00 UTC"

Here is what is not working, but I'd like to have working:

> as.POSIXct("25/03/2011 9:15:00 p.m.", format="%d/%m/%Y %I:%M:%S %p", tz="UTC")
[1] NA

I'm using R version 2.13.2 (2011-09-30) on MS Windows. My working locale is "C":

Sys.setlocale("LC_TIME", "C")

回答1:


It appears the AM/PM indicator can't include punctuation. Try it after removing the punctuation:

td <- "25/03/2011 9:15:00 p.m."
tdClean <- gsub("(.)\\.?[Mm]\\.?","\\1m",td)
as.POSIXct(tdClean, format="%d/%m/%Y %I:%M:%S %p", tz="UTC")
# [1] "2011-03-25 21:15:00 UTC"



回答2:


Just came across this, as another option you can use stringr package.

library(stringr)
data$date2 <- str_sub(data$date, end = -4) 
# this removes the punctuation but holds onto the A/P values
data$date2 <- str_c(data$date2, 'm') 
# adds the required m


来源:https://stackoverflow.com/questions/7883806/parse-timestamp-with-a-m-p-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!