as.POSIXct with datetimes including midnight

对着背影说爱祢 提交于 2019-12-29 01:49:09

问题


I am wanting to convert date-times stored as characters to date-time objects. However if a date time includes midnight then the resulting datetime object excludes the time component, which then throws an error when used in a later function (not needed here - but a function that extracts weather data for specified location and date-time).

Example code:

example.dates <- c("2011-11-02 00:31:00","2011-11-02 00:00:00","2011-11-02 00:20:22")
posix.dates   <- as.POSIXct(example.dates, tz="GMT", format="%Y-%m-%d %H:%M:%S")
posix.dates
posix.dates[2]

NB times is only excluded when the datetime containing midnight is called on it's own (atomic vector).

Is there a way of retaining the time data for midnight times? Can you suggest an alternative function?


回答1:


Okay, after some time I can reconfirm your problem.

For me this looks like a bug in R. I would suggest you to report it on https://bugs.r-project.org/bugzilla3/.

As a temporary workaround, you could try if it helps to overwrite the strptime function like this:

strptime <- function (x, format, tz = "") 
{
    if ("POSIXct" %in% class(x)) {
        x
    } else {
        y <- .Internal(strptime(as.character(x), format, tz))
        names(y$year) <- names(x)
        y
    }
}



回答2:


I prefer to use the lubridate package for date-times. It does not seem to cause problems here either:

example.dates <- c("2011-11-02 00:31:00","2011-11-02 00:00:00","2011-11-02 00:20:22")
library(lubridate)
ymd_hms(example.dates)



回答3:


lubridate::as_datetime() is more flexible, accepting both dates (interpreted as 00:00:00) and datetimes.

example.dates <- c("2011-11-02", "2011-11-02 00:31:00","2011-11-02 00:00:00","2011-11-02 00:20:22")
library(lubridate)

ymd_hms(example.dates)
#> Warning: 1 failed to parse.
#> [1] NA                        "2011-11-02 00:31:00 UTC"
#> [3] "2011-11-02 00:00:00 UTC" "2011-11-02 00:20:22 UTC"

as_datetime(example.dates)
#> [1] "2011-11-02 00:00:00 UTC" "2011-11-02 00:31:00 UTC"
#> [3] "2011-11-02 00:00:00 UTC" "2011-11-02 00:20:22 UTC"



回答4:


Realise this is an old question now, but I had the same issue and found this solution:

https://stackoverflow.com/a/51195062/8158951

Essentially, all you need to do is apply formatting as follows. The OP's code needed to include the formatting call after the POSIXct function call.

posix.dates <- format(as.POSIXct(example.dates, tz="GMT"), format="%Y-%m-%d %H:%M:%S")

This worked for me.



来源:https://stackoverflow.com/questions/19756771/as-posixct-with-datetimes-including-midnight

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