road_to_quantdom
road_to_quantdom

Reputation: 1361

How to convert to datetime object?

I have dates stored in this format (column one of my data)

> tmp[[1]]
# YYYYMMDD
19980102

And I have time store in this format (column two of my data)

> tmp[[2]]
#HHMM
0930

I was wondering how I could get this stored as a date-time format in R. I have tried using:

as.POSIXlt(paste(tmp[[1]], tmp[[2]]), format="%Y%m%d %H%M%S")

but my output is a bunch of NA's

NA

Upvotes: 0

Views: 36

Answers (1)

bgoldst
bgoldst

Reputation: 35314

You're almost there. Your main problem is the incorrect use of the %S format specifier on the end of the format string, when there are no actual seconds digits in the time field. Also, I changed paste() to paste0() and removed the space in the format string, although that's insignificant.

tmp <- data.frame(date='19980102', time='0930', stringsAsFactors=F );
as.POSIXlt(paste0(tmp$date,tmp$time), format='%Y%m%d%H%M' );
## [1] "1998-01-02 09:30:00 EST"

Upvotes: 1

Related Questions