Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
616 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...