Convert military time to standard time with hours and minutes in R

后端 未结 2 1292
离开以前
离开以前 2021-01-15 20:30

I have the following set of times data, that I have to convert into 12 hour format.

-----------------
814
830
1835
1730
1442
820
1430
930
1550
1725
1615
1010         


        
2条回答
  •  再見小時候
    2021-01-15 21:06

    This should work:

    myMtime #time vector
    myMtime <- sprintf("%04d", myMtime)
    myStdTime <- as.POSIXct(myMtime, format = "%H%M", origin = "1970-01-01", tz = "UTC")
    myStdTime #time as unix standard for time zone UTC
    

    Note that R will automatically add the year-month-day of the day you are converting myMtime. If you want to add a specific date, do the following:

    myMtime #time vector
    date <- "2016-01-01"
    myMtime <- sprintf("%04d", myMtime)
    myStdTime <- as.POSIXct(paste0(date, " ", myMtime), format = "%Y-%m-%d %H%M", origin = "1970-01-01", tz = "UTC")
    myStdTime #time as unix standard for time zone UTC
    

    For the output format use format:

    format(myStdTime, format = "%r%p")
    #or thing like that:
    format(myStdTime, format = "%a %b %d %X %Y %Z")
    #for further explanations consider:
    ?strptime
    

提交回复
热议问题