Converting dates into numbers

1 Ansicht (letzte 30 Tage)
Sergio
Sergio am 10 Sep. 2013
Beantwortet: Peter Perkins am 12 Sep. 2018
I have a int32 matrix of dates in the format YYYYMMDD and a cell array for time in the day in the format HH:MM. How can I combine both and turn it into a number I can use for plotting?

Akzeptierte Antwort

Azzi Abdelmalek
Azzi Abdelmalek am 10 Sep. 2013
x=int32([19921212,19921213,19921214])'
y={'12:12', '13:13','14:14'}'
a=[num2str(x) char(y)]
b=datenum(a,'yyyymmddHH:MM')
datestr(b)
  3 Kommentare
Silver
Silver am 11 Sep. 2018
@Azzi and when I have the date format already sticked together like this: 2016.03.01 14:38:00 in a cell array how can I convert them to numeric so I can ue them in plot ? thks in advance
Stephen23
Stephen23 am 11 Sep. 2018
@Silver: read the datenum documentation.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Peter Perkins
Peter Perkins am 12 Sep. 2018
Unless you're using a fairly old version of MATLAB, consider using datetimes instead of datenums. You will be happier.
>> x = int32([19921212,19921213,19921214])';
>> y = {'12:12', '13:13','14:14'}';
>> d = datetime(x,'ConvertFrom','yyyymmdd')
d =
3×1 datetime array
12-Dec-1992 00:00:00
13-Dec-1992 00:00:00
14-Dec-1992 00:00:00
>> t = duration(y,'InputFormat','hh:mm')
t =
3×1 duration array
12:12:00
13:13:00
14:14:00
>> dt = d + t
dt =
3×1 datetime array
12-Dec-1992 12:12:00
13-Dec-1992 13:13:00
14-Dec-1992 14:14:00
Then just plot whatever vs. dt. You don't need to convert the datetimes to numeric.
Actually, creating the duration directly form text requires R2018a, prior to that do this:
>> t = timeofday(datetime(y,'InputFormat','HH:mm'))
t =
3×1 duration array
12:12:00
13:13:00
14:14:00
or use text2duration on the File Exchange.

Kategorien

Mehr zu Dates and Time finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by