将 12 小时制转换为 24 小时制

编程入门 行业动态 更新时间:2024-10-28 19:25:57
本文介绍了将 12 小时制转换为 24 小时制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有每小时的天气数据.我从这里看到了函数示例:http://casoilresource.lawr.ucdavis.edu/drupal/node/991

I have hourly weather data. I've seen the function examples from here: http://casoilresource.lawr.ucdavis.edu/drupal/node/991

我正在更改代码以考虑机场数据,该数据具有不同的 URL 类型.机场天气数据的另一个问题是时间数据以 12 小时格式保存.以下是数据示例:

I'm altering the code to account for airport data, which has a different URL type. Another issue with the airport weather data is that the time data is saved in 12 hour format. Here is a sample of the data:

14  10:43 AM
15  10:54 AM
16  11:54 AM
17  12:07 PM
18  12:15 PM
19  12:54 PM
20  1:54 PM
21  2:54 PM

这是我尝试过的:(我发现仅使用PM"不够谨慎,因为如果他们通过此算法,下午 12 点到 1 点之间的任何时间都会关闭)

Here's what I attempted: (I see that using just 'PM' isn't careful enough because any times between 12 and 1 pm will be off if they go through this alg)

date<-Sys.Date()


data$TimeEST<-strsplit(data$TimeEST, ' ')
for (x in 1:35){
    if('AM' %in% data$TimeEST[[x]]){
        gsub('AM','',data$TimeEST[[x]])
        data$TimeEST[[x]]<-str_trim(data$TimeEST[[x]])
        data$TimeEST[[x]]<-str_c(date,' ',data$TimeEST[x],':',data$TimeEST[2])
    }
    else if('PM' %in% data$TimeEST[[x]]){
        data$TimeEST[[x]]<-gsub('PM', '',data$TimeEST[[x]])
        data$TimeEST[[x]]<-strsplit(data$TimeEST[[x]], ':')
        data$TimeEST[[x]][[1]][1]<-as.integer(data$TimeEST[[x]][[1]][1])+12
        data$TimeEST[[x]]<-str_trim(data$TimeEST[[x]][[1]])
        data$TimeEST[[x]]<-str_c(date, " ", data$TimeEST[[x]][1],':',data$TimeEST[[x]][2])

    }
}

有什么帮助吗?

推荐答案

strptime 会起作用吗?

df2= structure(c("10:43 AM", "10:54 AM", "11:54 AM", "12:07 PM", "12:15 PM", 
            "12:54 PM", "1:54 PM", "2:54 PM"), .Dim = c(8L, 1L))



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

或者,如果您不想要日期,例如:尽管这取决于您希望该对象使用哪种类.

Or in case you don't want the date, something like: Although it depends what kind of class would you want for the object.

substr(strptime(df2, "%I:%M %p" ),11,19)

这篇关于将 12 小时制转换为 24 小时制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 13:07:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1395098.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:小时   转换为

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!