[英]Convert 12 hour character time to 24 hour
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.
我试图将其从 12 小时制转换为 24 小时制。我进行了一些搜索,但我发现的所有内容似乎都假设字符已经采用 24 小时制。 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. @Tyler - 你打字比我快。 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
To Topic Starter - 请查看 CDT 和 EDT 是如何根据您的时区自动填充的 - 在一天中 1 小时内转换时间时,这可能是一个潜在的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.