将 HH:MM:SS AM/PM 字符串转换为时间 [英] Convert HH:MM:SS AM/PM string to time

查看:53
本文介绍了将 HH:MM:SS AM/PM 字符串转换为时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以1:36:22 PM"等字符格式解析时间.

I need to parse times in a character format like "1:36:22 PM".

我已经尝试了 as.POSIXctstrptime 的各种排列,但就是无法到达那里.例如,这没有体现 PM 的重要性:

I've tried various permutations of as.POSIXct and strptime but just can't get there. For example, this fails to pick up the importance of PM:

t <- "1:36:22 PM"
as.POSIXct(t, format = "%H:%M:%S")
# [1] "2016-09-08 01:36:22 BST"

这失败了:

strptime(t, "%H:%M:%S")
# [1] NA

奇怪的是,出于我无法理解的原因,从输入中删除秒数可能可行:

Curiously, for reasons I can't understand, dropping the seconds from the input may work:

t <- "1:30:00 PM"
strptime(t, "%I:%M %p")
# [1] NA
 
t <- "1:30 PM"
strptime(t, "%I:%M %p")
# [1] "2016-09-08 13:30:00 BST"

我想要的只是让它起作用:

All I want is for this to work:

t <- "1:30:00 PM"
SOME COMMAND HERE HERE
# [1] "13:30:00"

有什么想法吗?

推荐答案

您是否尝试过使用 lubridate 包?它可以使用parse_date_time"函数中的%p指标来处理上午/下午.

Have you tried using the lubridate package? It can handle AM/PM using the %p indicator in the "parse_date_time" function.

library(lubridate)
t <- "1:36:22 PM"
parse_date_time(t, '%I:%M:%S %p')
[1] "2016-09-08 13:36:22 UTC"

来自 lubridate 文档:

%I: 十进制的小时数(01–12 或 1–12).

%M: 十进制数的分钟(00–59 或 0–59).

%S: 第二个十进制数(00–61 或 0–61).

%P: 区域设置中的 AM/PM 指示符.与 I 结合使用,而不与 H 结合使用.在某些语言环境中为空字符串.

这篇关于将 HH:MM:SS AM/PM 字符串转换为时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆