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
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"
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.
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
}
}
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)