Transfer hh:mm (Time) into "double"
Show older comments
Hello,
I have written a program, that calculates the cheapest way to charge an EV based on dynamic elctricity prices. As an input the program uses the Arrival and Departure time of the user in 'double'. So if the vehicle arrives at "10:30 am" the arrival parameter is 10,5. It gets even more complicated if the arrival time is e.g. "10:31". The value should then be 10,5166666666..... This is quite cumbersome.
Is there any way to transfer "hh:mm" into a double value?
Greetings
Alex
Accepted Answer
More Answers (1)
Steven Lord
on 3 Apr 2019
Consider this technique:
rightnow = datetime('now');
midnight = dateshift(rightnow, 'start', 'day');
timeSinceMidnight = rightnow-midnight
hours(timeSinceMidnight)
I used datetime arithmetic in constructing the duration timeSinceMidnight, but you can construct it by calling duration if you want.
d = duration('10:31', 'InputFormat', 'hh:mm')
hours(d)
1 Comment
Peter Perkins
on 9 Apr 2019
Something close to Steve Lord's datetime solution is really the right way to do this in general. With simple mods, it can work even if the arrival/departure straddle midnight (or a DST shift, and will easily handle a 12 hr clock.
>> arrive = datetime('10:31 am', 'InputFormat', 'hh:mm a')
arrive =
datetime
08-Apr-2019 10:31:00
>> depart = datetime('12:41 pm', 'InputFormat', 'hh:mm a')
depart =
datetime
08-Apr-2019 12:41:00
>> hours(depart - arrive)
ans =
2.1667
When dealing with time in MATLAB, best to use the time/date tools it provides.
Actually, the whole thing is ill-posed unless one assumes the charging stations close before midnight, or that there's a date portion to the data.
Categories
Find more on Time Series Objects in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!