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
I want all times to be in %H :%M :%S
format i.e 02:30:15, 03:45:00, 09:45:30