简体   繁体   中英

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!

One way would be to use sprintf :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM