Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
608 views
in Technique[技术] by (71.8m points)

r - as.POSIXct with datetimes including midnight

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...