How to convert Redis date in R [closed]

2019-09-21 07:08发布

I am trying to convert this kind of date: "Tue Aug 12 2014 19:47:50 GMT+0000 (UTC)"

parseRedisDate <- function(date) {
    x <- gsub(" GMT\\+0000 \\(UTC\\)", "", date)
    as.Date(x, format="%a %b %d %Y %T")
}
date <- "Tue Aug 12 2014 19:47:50 GMT+0000 (UTC)"
parseRedisDate(date)

Not working...

2条回答
Juvenile、少年°
2楼-- · 2019-09-21 07:19

You don't want to use date as an object name, since that's a function in base R. But otherwise your function seems to work. The core bit of it:

x <- as.Date(gsub(" GMT\\+0000 \\(UTC\\)", "",
                  'Tue Aug 12 2014 19:47:50 GMT+0000 (UTC)'),
             format="%a %b %d %Y %T")
x

returns:

[1] "2014-08-12"

and

class(x)

returns:

[1] "Date"
查看更多
甜甜的少女心
3楼-- · 2019-09-21 07:44

If you need the full datetime, you can easily coerce that string to an object of class POSIXct:

    x<-"Tue Aug 12 2014 19:47:50 GMT+0000 (UTC)"
    as.POSIXct(x,format="%a %b %d %Y %H:%M:%S")

This may fail if your locale isn't set to understand the English month and day names. You can set the locale through:

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

and the above commands will work. If you just need the date (without the time), you can coerce the POSIXct to Date:

    as.Date(as.POSIXct(x,format="%a %b %d %Y %H:%M:%S"))
查看更多
登录 后发表回答