Vicki1227
Vicki1227

Reputation: 151

convert character time like "700" to strptime 07:00 in R

sleep$Ending <- as.POSIXct(as.character(sleep$END),format=" %H%M")

Hi, the Ending variable is in numeric format representing time. For example, "0" is 00:00, "1450" is 14:50. I would like to convert it into strptime to calculate time difference. I thought using something like the above code should work. However, for cases when "Ending" time is less than 4-digit, say "0","700", these won't work.

Can someone help me? Thanks very much!

Upvotes: 0

Views: 107

Answers (1)

lukeA
lukeA

Reputation: 54247

One way would be to use sprintf:

as.POSIXct(sprintf("%04d", 700),format="%H%M")
# [1] "2015-10-29 07:00:00 CET"

Upvotes: 4

Related Questions