How to convert time (duration) to datetime?
Show older comments

In the data above, the column time shows 10:30:41 AM; 08:2007 AM etc. but the class of the variable Time is duration.
I want to convert these values to datetime.
When I try:
m.Time=datetime(m.Time, 'Format', 'HH:mm:ss');m.Time=datetime(m.Time, 'Format', 'HH:mm:ss');
I get an error:
Input data must be a numeric array, a string array, a cell array containing character vectors, or a char matrix.
Answers (1)
dpb
on 13 Mar 2020
The datetime class cannot exist without both a date and a time component. You'll have to assign a date as well...
du=duration(10,30,41);
dt=datetime(date)+du; % combine with today's date
>> dt
dt =
datetime
12-Mar-2020 10:30:41
>>
dt.Format='HH:mm:ss';
>> dt
dt =
datetime
10:30:41
>>
The value still includes the date of course, but only shows the time portion.
Seems awkward at times, but is "simply the way it is". If want to use the class, must follow the rules thereof.
4 Comments
Louise Wilson
on 13 Mar 2020
Steven Lord
on 13 Mar 2020
As dpb said, the best way to convert the duration objects to datetime is by adding them to a "base date". That first entry represents 10 hours, 30 minutes, 41 seconds, but 10:30:41 after when? The start of today? The start of tomorrow? That's the information only you know.
Louise Wilson
on 13 Mar 2020
Walter Roberson
on 13 Mar 2020
No do not datetime the duration. duration() it. If you have a newer matlab you can pass in the strings; older matlab you had to split the strings into numeric components and pass the numeric components in.
Once you have the duration, add it to the datetime created by the date string.
Categories
Find more on Data Type Conversion 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!