Combining Date and Time variables (class - datetime) into 1 DateTime (class - double) array
Afficher commentaires plus anciens
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
Réponse acceptée
Plus de réponses (1)
Peter Perkins
le 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 commentaires
Jenny
le 26 Nov 2014
Peter Perkins
le 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]
Catégories
En savoir plus sur Time Series Objects dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!