as.POSIXct with datetimes including midnight

前端 未结 4 1803
醉话见心
醉话见心 2020-12-12 00:47

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 c

相关标签:
4条回答
  • 2020-12-12 01:24

    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"
    
    0 讨论(0)
  • 2020-12-12 01:24

    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.

    0 讨论(0)
  • 2020-12-12 01:26

    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
        }
    }
    
    0 讨论(0)
  • 2020-12-12 01:31

    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)
    
    0 讨论(0)
提交回复
热议问题