Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a number into time (0,5 of an hour = 00:30:00)

Tags:

time

r

I am trying to convert a number into time format. For example: I calculate how long has to be charged an electric car at the charging station of 11 kWh.

  • Energy demand - 2,8 kWh
  • Charging time = 2,8 kWh/11 kWh = 0,257 h
  • 0,257 h = 15 min 25 sec. = 00:15:25

How can I convert 0,257 h into 00:15:25 in R?

like image 755
Inna Avatar asked Jan 17 '18 13:01

Inna


People also ask

How do you convert time into hours?

To convert time to a number of hours, multiply the time by 24, which is the number of hours in a day. To convert time to minutes, multiply the time by 1440, which is the number of minutes in a day (24*60).

How do you convert time into minutes?

What is the rule for converting hours to minutes? The rule for converting hours to minutes is very simple, just multiply the number of hours by 60 and you will get the time in minutes. For example, to convert 2 hours into minutes, multiply 2 by 60, and you will get 120 minutes.

How do you convert a number to time in python?

​ hours = int(time) minutes = (time*60) % 60. seconds = (time*3600) % 60. ​ print("%d:%02d. %02d" % (hours, minutes, seconds)) >> 72:20:42.


1 Answers

Based on the example, we will assume that the input is less than 24 (but if that is not the case these could be modified to handle that depending on the definition of what such an input should produce).

1) chron::times Use chron times like this. times measures times in fractions of a day so divide the hours (.257) by 24 to give the fraction of a day that it represents.

library(chron)

times(.257 / 24)
## [1] 00:15:25

This gives a chron "times" class object. If x is such an object use format(x) to convert it to a character string, if desired.

2) POSIXct This uses no packages although it is longer. It returns the time as a character string. POSIXct measures time in seconds and so multiply the hours (.257) by 3600 as there are 3600 seconds in an hour.

format(as.POSIXct("1970-01-01") + 3600 * .257, "%H:%M:%S")
## [1] "00:15:25"

2a) This variation would also work. It is longer but it involves no conversion factors. It returns a character string.

format(as.POSIXct("1970-01-01") + as.difftime(.257, units = "hours"), "%H:%M:%S")
## [1] "00:15:25"

Updates: Added (2). Also added (2a) and improved (2).

like image 169
G. Grothendieck Avatar answered Sep 28 '22 20:09

G. Grothendieck