Convert 12 hour character time to 24 hour

后端 未结 2 780
花落未央
花落未央 2020-11-30 09:20

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

相关标签:
2条回答
  • 2020-11-30 09:42

    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"
    
    0 讨论(0)
  • 2020-11-30 09:56
    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

    0 讨论(0)
提交回复
热议问题