3

Why does as_datetime() result in NA in the below example?

x <- dmy("1-1-2000")
y <- "14:30"
as_datetime(paste(x, y))

Error:

[NA]
Warning message:
All formats failed to parse. No formats found.

Thank you

Andrea
  • 607
  • 8
  • 21

2 Answers2

4

We can use the format argument

library(lubridate)
as_datetime(paste(x, y), format = "%Y-%m-%d %H:%M")
#[1] "2000-01-01 14:30:00 UTC"

Or another option is anytime

library(anytime)
anytime(paste(x, y))
#[1] "2000-01-01 14:30:00 EST"

The reason could be that it expectss the time to be in %H:%M:%S format, which the 'y' is not. If we use the full format instead of %H:%M (which can also be judged as %M:%S)

y1 <- "14:30:00"
as_datetime(paste(x, y1))
#[1] "2000-01-01 14:30:00 UTC"

NOTE: This answers why the OP get a warning message.

akrun
  • 874,273
  • 37
  • 540
  • 662
3

As you are using lubridate already, you just need to add the date object dmyto the time object (hour : min) by setting hm before.

x <- dmy("1-1-2000") 
y <- "14:30" 
z <- x + hm(y) 

See : R tick data : merging date and time into a single object

tom
  • 725
  • 4
  • 17
  • Hello @tdel, thank you for the solution. I used this method on a dataframe and it worked for parsing two columns, however it is failing at the rows in which the times are at hour zero (ex. 00:34). Any idea why? – Andrea Jul 13 '19 at 15:46