英文:
Convert time string with both am/pm and 24 hour format in R
问题
我有一个包含在我的df
列中的时间列表,如下所示:
times <- c("11:30am", "3:15pm", "2:25pm", "12:05pm", "8:25pm", "7:52pm", "13:22", "18:45", "21:14", "11:20")
我该如何将这些时间转换为正确的格式?
我希望将带有上午/下午标记的时间去除标记并转换为24小时制,对于那些已经处于正确格式的时间,将其转换为时间格式。
期望的输出:
11:30
15:15
14:25
12:05
20:25
19:52
13:22
18:45
21:14
11:20
我尝试过以下代码:
times <- ifelse(grepl('am', times) | grepl('pm', times),
as.POSIXct(times, format = "%I:%M%p"), as.POSIXct(times, format="%H:%M"))
但它只给我返回了一组数字。
英文:
I have a list of times in my df
column like so:
times <- c("11:30am", "3:15pm", "2:25pm", "12:05pm", "8:25pm", "7:52pm", "13:22", "18:45", "21:14", "11:20")
How can I convert the times to time format so they are all formatted correctly?
I would like the am/pm to be removed from those that have it and converted to 24 hr time, and for those that are already in the correct format, to be converted to time format.
Desired output:
11:30
15:15
14:25
12:05
20:25
19:52
13:22
18:45
21:14
11:20
I tried:
times <- ifelse(grepl('am', times) | grepl('pm', times),
as.POSIXct(times, format = "%I:%M%p"), as.POSIXct(times,format="%H:%M"))
But it just gave me a list of numbers.
答案1
得分: 5
你可以使用正则表达式来检测输入值的格式。
然后根据小时输入的格式来调整strptime
的参数。
ifelse(grepl("am|pm", times),
format(strptime(times, "%I:%M %p"), format="%H:%M"),
format(strptime(times, "%H:%M"), format="%H:%M"))
[1] "11:30" "15:15" "14:25" "12:05" "20:25" "19:52" "13:22" "18:45" "21:14" "11:20"
英文:
You can use a regular expression to detect the format of the input value.
Then adjust the argument of strptime
depending on the hour input format.
ifelse(grepl("am|pm", times),
format(strptime(times, "%I:%M %p"), format="%H:%M"),
format(strptime(times, "%H:%M"), format="%H:%M"))
[1] "11:30" "15:15" "14:25" "12:05" "20:25" "19:52" "13:22" "18:45" "21:14" "11:20"
答案2
得分: 2
你可以这样做:
sapply(strsplit(times, ":"), function(x) {
h <- as.numeric(x[1]) + grepl("pm", x[2]) * 12
if (h == 24) h <- 12
if (h == 12 & grepl("am|pm", x[2])) h <- 0
paste(sprintf("%02d", h),
gsub("^(\\d+).*$", "\", x[2]), sep = ":")
})
#> [1] "11:30" "15:15" "14:25" "00:05" "20:25" "19:52" "13:22" "18:45"
#> [9] "21:14" "11:20"
英文:
You could do:
sapply(strsplit(times, ":"), function(x) {
h <- as.numeric(x[1]) + grepl("pm", x[2]) * 12
if(h == 24) h <- 12
if(h == 12 & grepl("am|pm", x[2])) h <- 0
paste(sprintf("%02d", h),
gsub("^(\\d+).*$", "\", x[2]), sep = ":")
})
#> [1] "11:30" "15:15" "14:25" "00:05" "20:25" "19:52" "13:22" "18:45"
#> [9] "21:14" "11:20"
答案3
得分: 0
使用 parse_date
library(parsedate)
format(parse_date(times), "%H:%M")
输出
[1] "11:30" "15:15" "14:25" "12:05" "20:25" "19:52" "13:22" "18:45" "21:14" "11:20"
英文:
Using parse_date
library(parsedate)
format(parse_date(times), "%H:%M")
-output
[1] "11:30" "15:15" "14:25" "12:05" "20:25" "19:52" "13:22" "18:45" "21:14" "11:20"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论