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")
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"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With