Reputation: 780
I have the following data
>d
2010-07-02
>t
835
I issue the following command
>dt<-paste(d,t)
>dt
"2010-07-02 835"
i then issue the following command, and it returns NA as below:
>dtt<-as.POSIXlt(strptime(dt,'%Y-%m-%d %H%M'))
>dtt
NA
so I made the following change
>t=1001
and now when I run dt followed by dtt, it works fine, returning
dtt "2010-07-02 10:01:00"
so, it seems to me that it is having a problem with the first digit of the hour being a 0, which is why when HHMM is less than 1000, it generates NA. can anyone please suggest how I fix this. thanks!
Upvotes: 2
Views: 3365
Reputation: 179388
Use sprintf
to format your time string before you pass it to as.POSIXlt
:
d <- "2010-07-02"
h <- 835
dtt <- sprintf("%s %04d", d, h)
as.POSIXlt(dtt, format="%Y-%m-%d %H%M")
[1] "2010-07-02 08:35:00"
The string "%s %04d"
tells sprintf
to concatenate d as a string (%s) and h as a fixed width string of length 4, with leading zeroes (%04d).
Upvotes: 4