user2350366
user2350366

Reputation: 511

Trying to append dates in R but the time component is being dropped?

I have come across this problem. Consider an array of dates:

> y <- c("2012-01-02 10:00:00", "2012-01-03 09:00:00")
> as.POSIXct(y)
[1] "2012-01-02 10:00:00" "2012-01-03 09:00:00"

Now consider the same array with "2012-01-04 00:00:00". This vector has already undergone as.POSIXct, hence we get c("2012-01-02 10:00:00", "2012-01-03 09:00:00", "2012-01-04"). Then

> y <- c("2012-01-02 10:00:00", "2012-01-03 09:00:00", "2012-01-04")
> as.POSIXct(y)
[1] "2012-01-02 GMT" "2012-01-03 GMT" "2012-01-04 GMT"

Now the times have been dropped from all the dates rather than just adding back 00:00:00 to 2012-01-04. I've played around with formatting POSIXct and strptime, but am not getting anywhere. For example:

> as.POSIXct(strptime("2011-03-27 00:00:00", "%Y-%m-%d %H:%M:%S"))
[1] "2011-03-27 GMT"

How can I retrieve the correct values?

Upvotes: 1

Views: 45

Answers (1)

akrun
akrun

Reputation: 887531

This can be solved by using anytime

anytime::anytime(y)
#[1] "2012-01-02 10:00:00 IST" "2012-01-03 09:00:00 IST" "2012-01-04 00:00:00 IST"

Note that anytime have a default set of formats. We can find those with getFormats(). If the format is not in the list, then use the addFormats to add a format


Or another way is by using parse_date_time from lubridate

lubridate::parse_date_time(y, guess_formats(y, c('ymd', 'ymd_HMS')))
#[1] "2012-01-02 10:00:00 UTC" "2012-01-03 09:00:00 UTC" "2012-01-04 00:00:00 UTC"

We guess the problem stems from the multiple format in the input vector and as.POSIXct takes only a single format, so probably it unifies the format to a single one by removing the time substring from the other elements. This was tested on R 3.4.0 and on R 3.1.3 and both get the same output as in the OP's post

Upvotes: 2

Related Questions