Combining Date and Time variables (class - datetime) into 1 DateTime (class - double) array
13 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
Star Strider
il 31 Ott 2014
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.
7 Commenti
Più risposte (1)
Peter Perkins
il 25 Nov 2014
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 Commenti
Peter Perkins
il 26 Nov 2014
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]
Vedere anche
Categorie
Scopri di più su Dates and Time in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!