Combining Date and Time variables (class - datetime) into 1 DateTime (class - double) array
2 次查看(过去 30 天)
显示 更早的评论
I import my data with:
Date = dataArray{:, 6}; Time = dataArray{:, 7};
Date as a 'datetime' value with format: 'dd.mm.yyyy' and
Time as a 'datetime' value with format: 'HH:MM'.
I can convert both of these using datenum:
Date2=datenum(Date); Time2=datenum(Time);
How do I now combine Date2 and Time2 to make one DateTime array?
Example: Date= 06.07.2010
06.07.2010
Time= 22:31
22:41
Date2 = 7.341440048611110e+05
7.341440048611110e+05
Time2 = 7.359039381944444e+05
7.359039451388889e+05
I tried including a format specification in the datenum code line but kept on getting an error (Erro using Datetime/datenum - Too many input arguments)
Date2 = datenum(Date, 'dd.mm.yyyy');
Time2 = datenum(Time, 'HH:MM');
I would like to generate one DateTime array that would look as follows as a string:
06.07.2010 22:31
06.07.2010 22:41
Thanks in advance, Jenny
0 个评论
采纳的回答
Star Strider
2014-10-31
I haven’t used the new datetime functions much, and I don’t have your array. This works on the example you gave:
Date = datetime('06.07.2010','InputFormat','dd.MM.yyyy');
Time = datetime('22:31','InputFormat','HH:mm');
CnvtDT = @(Date,Time) datetime([Date.Year Date.Month Date.Day Time.Hour Time.Minute 0], 'Format', 'dd.MM.yyyy HH:mm');
DateTime2 = CnvtDT(Date,Time) % Check Output
The output is also a ‘datetime’ structure.
更多回答(1 个)
Peter Perkins
2014-11-25
Jenny, if you create datetimes from strings and don't specify the time portion, it defaults to midnight. If you don't specify the date portion, it defaults to "today". So
>> Date = datetime('06.07.2010','InputFormat','dd.MM.yyyy')
Date =
06-Jul-2010
>> Time = datetime('22:31','InputFormat','HH:mm')
Time =
25-Nov-2014 22:31:00
Then all you need to do is extract the time of day from the second array
>> timeofday(Time)
ans =
22:31:00
and add that to the first array:
>> DateAndTime = Date + timeofday(Time)
DateAndTime =
06-Jul-2010 22:31:00
Hope this helps.
2 个评论
Peter Perkins
2014-11-26
Two things:
1) You've used 'mm' where you want 'MM': the format to textscan should be %{dd.MM.yyyy}D. I don't have your file, but I assume that's why you get 38, 48, etc.
2) All you need to do is to set the format. Your Date and Time variables have the formats from your call to textscan, and Date+timeofday(Time) preserves the format of Date. So set the format of the result to whatever you want. Perhaps like this
DateAndTime.Format = [Date.Format ' ' Time.Format]
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!