Home > OS >  How to convert a 12 hour time stamp (NOT a datetime, time only) to 24 hour time?
How to convert a 12 hour time stamp (NOT a datetime, time only) to 24 hour time?

Time:01-23

I have a character column containing times in the 12 hour format, for example: 2:59:00 PM, 4:35:00 AM, 6:00:00 PM, etc.

How can I convert these to 24 hour time using lubridate (or some other function)? I tried using the HMS functions but it just strips the AM/PM without actually converting the time to 24 hour time...

EDIT: I tried the answer from this post: enter image description here

c("2:59:00 PM", "4:35:00 AM", "6:00:00 PM", "6:00:00 PM", "6:00:00 PM", "6:00:00 PM", "6:00:00 PM", "6:00:00 PM", "5:35:00 AM")

CodePudding user response:

Try

lab_data[,LAB_TM_test:=as.POSIXct(LAB_TM, format='%I:%M:%S %p')]

CodePudding user response:

This is a base R solution, using strptime to convert to 24h-format and strftime to only print the time.

df$LAB_TM_new <- strftime(strptime(df$LAB_TM, format="%I:%M:%S %p"), format="%H:%M:%S")

df
      LAB_TM LAB_TM_new
1 2:59:00 PM   14:59:00
2 4:35:00 AM   04:35:00
3 6:00:00 PM   18:00:00
4 6:00:00 PM   18:00:00
5 6:00:00 PM   18:00:00
6 6:00:00 PM   18:00:00
7 6:00:00 PM   18:00:00
8 6:00:00 PM   18:00:00
9 5:35:00 AM   05:35:00
  •  Tags:  
  • Related