How to convert time (duration) to datetime?

조회 수: 212 (최근 30일)
Louise Wilson
Louise Wilson 2020년 3월 13일
댓글: Walter Roberson 2020년 3월 13일
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.

답변 (1개)

dpb
dpb 2020년 3월 13일
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
Louise Wilson
Louise Wilson 2020년 3월 13일
Thanks for getting back Steven. The purpose of this was to get some data from a .csv which has a date column and a time (duration) column and combine them to get a datetime, so I am adding the duration to a base date, I think. Do you see a more refined way of doing this?? I think this is perhaps quite backwards...
clc;clear;
m=readtable('G:\My Drive\Results\Tawh.csv'); %read in table
m.Date=datetime(m.Date, 'Format', 'dd/MM/yyyy'); %read columns as datetime values
m.Time=datetime(datevec(m.Time),'Format','HH:mm:ss');
m.Date.Format='dd.MM.uuuu HH:mm'; %change the display format to view both date and time info.
m.Time.Format='dd.MM.uuuu HH:mm';
m.DateTime = m.Date + timeofday(m.Time);
Walter Roberson
Walter Roberson 2020년 3월 13일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Dates and Time에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by