0

I have a data frame with dates and times in two different columns as factors - df$date and df$time. I'm able to convert df$date from factor to date format. However there's an issue with the df$time column. Some times are in the H:M:S format while some are in the HMS format. For eg row 1 has time 02:30:15 while row 2 has time 0345, row 3 might have something like 094530. (The colons are missing)

#converting into posixct format
df$newtime <-as.POSIXct(df$time,format="%H: %M :%S")

However this generates random dates but correct time, so I used strptime to remove years month and date

df$newtime1 <- format(as.POSIXct(strptime(df$newtime,"%Y-%m-%d %H:%M:%S",tz="")) ,format = "%H:%M:%S")

This gives me correct time in hours minutes and seconds. However it generates a few NAs because some time rows don't have colons (0345 instead of 03:45)

The image shows my desired output

enter image description here

I want all times to be in %H :%M :%S format i.e 02:30:15, 03:45:00, 09:45:30

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
SUNNY
  • 1
  • 1
  • 2
    It's difficult to help debug without a [workable sample of your data](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). For working with multiple possible formats, [this](https://stackoverflow.com/q/13764514/5325862) is likely a dupe, but right now it's unclear – camille Aug 15 '19 at 22:19
  • Thanks for the help :) I've posted an image of the desired output – SUNNY Aug 15 '19 at 22:33
  • Please do *not* post images of input data Follow the instructions for asking questions at the top of the [tag:r] tag. – G. Grothendieck Aug 15 '19 at 23:00
  • use `lubridate::parse_date_time(df$newtime,c("ymdHM","ymdHMS"))` – Onyambu Aug 15 '19 at 23:52

0 Answers0