Home > Mobile >  I need to change the time format in my DataFrame
I need to change the time format in my DataFrame

Time:02-17

Hello people,

I have a Column of a dataframe that shows the time of a departure. The problem i have is that 6 am shows like 6:00 and I need it to be 06:00.

My dataframe looks like this:

Van ID Departure
0034 6:00
1973 12:00
7679 21:00
2532 9:00

And I need it to be like this:

Van ID Departure
0034 06:00
1973 12:00
7679 21:00
2532 09:00

Is there a function that helps me do this fast? I have like 2000 observations and I cant go one by one changing them.

Thanks!!!!

CodePudding user response:

In base R, can convert to Datetime object and then use format

df1$Departure <- format(as.POSIXct(df1$Departure, format = "%H:%M"), "%H:%M")

-output

> df1
  VanID Departure
1  0034     06:00
2  1973     12:00
3  7679     21:00
4  2532     09:00

Or may use regex replacement

df1$Departure <- sub("^(\\d):", "0\\1:", df1$Departure)

data

df1 <- structure(list(VanID = c("0034", "1973", "7679", "2532"), 
Departure = c("6:00", 
"12:00", "21:00", "9:00")), row.names = c(NA, -4L), class = "data.frame")
  •  Tags:  
  • r
  • Related