Convert decimal day to HH:MM

前端 未结 3 484
名媛妹妹
名媛妹妹 2020-12-03 18:02

I have a vector of decimal numbers, which represent \'decimal day\', the fraction of a day. I want to convert it into HH:MM format using R.

For example, the number

相关标签:
3条回答
  • 2020-12-03 18:49

    Try this:

    R> format(as.POSIXct(Sys.Date() + 0.8541667), "%H:%M", tz="UTC")
    [1] "20:30"
    R> 
    

    We start with a date--which can be any date, so we use today--and add your desired fractional day.

    We then convert the Date type into a Datetime object.

    Finally, we format the hour and minute part of the Datetime object, ensuring that UTC is used for the timezone.

    0 讨论(0)
  • 2020-12-03 18:49

    Using chron:

    chron::times(0.8541667)
    #[1] 20:30:00
    
    0 讨论(0)
  • 2020-12-03 19:00

    One option with data.table:

    > library(data.table)
    > structure(as.integer(0.4305556*60*60*24), class="ITime")
    [1] "10:20:00"
    

    We convert from day fraction to seconds since midnight; coerce to integer; and apply ITime class. (ITime works with integer-stored seconds since midnight.)

    Other resources:

    • @GaborGrothendieck re chron package and link to his R News article with Thomas Petzoldt about converting from Excel in particular Converting a time decimal/fraction representing days to its actual time in R?
    • @JorisChau re RStudio's hms package how to convert excel internal coding for hours to hours in R?
    0 讨论(0)
提交回复
热议问题