Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert 12 hour character time to 24 hour

Tags:

r

I have a data set with the time in character format. I’m attempting to covert this from a 12 hour format to 24. I have done some searching, but everything I have found seems to assume the characters are already in 24 hour format. Here is an example of the times I'm working with.

times <- c("9:06 AM", "4:42 PM", "3:05 PM", "12:00 PM", "3:38 AM")
like image 435
Galilean Moons Avatar asked Apr 23 '15 20:04

Galilean Moons


2 Answers

This should work:

times <- c("9:06 AM", "4:42 PM", "3:05 PM", "12:00 PM", "3:38 AM")

strptime(times, "%I:%M %p")

## [1] "2015-04-23 09:06:00 EDT" "2015-04-23 16:42:00 EDT"
## [3] "2015-04-23 15:05:00 EDT" "2015-04-23 12:00:00 EDT"
## [5] "2015-04-23 03:38:00 EDT"

If you want just the times:

format(strptime(times, "%I:%M %p"), format="%H:%M:%S")
## [1] "09:06:00" "16:42:00" "15:05:00" "12:00:00" "03:38:00"
like image 68
Tyler Rinker Avatar answered Oct 14 '22 08:10

Tyler Rinker


times <- c("9:06 AM", "4:42 PM", "3:05 PM", "12:00 PM", "3:38 AM")
print(as.POSIXct(times, format='%I:%M %p'))

[1] "2015-04-23 09:06:00 CDT" "2015-04-23 16:42:00 CDT" "2015-04-23 15:05:00 CDT" "2015-04-23 12:00:00 CDT"
[5] "2015-04-23 03:38:00 CDT"

@Tyler - you type faster than I do. To Topic Starter - please see how the CDT and EDT are auto-populated based on your Time Zone - this might be potentially an issue when converting times within 1 hour of the day change

like image 30
Alexey Ferapontov Avatar answered Oct 14 '22 07:10

Alexey Ferapontov