How to extract date, month, year, and time from a table data?
53 views (last 30 days)
Show older comments
I have a table data like "A" like this:
>> A(1:49,1)
ans =
49×1 table
DateTime
___________________
2016-01-01 00:30:00
2016-01-01 01:00:00
2016-01-01 01:30:00
2016-01-01 02:00:00
2016-01-01 02:30:00
2016-01-01 03:00:00
2016-01-01 03:30:00
2016-01-01 04:00:00
2016-01-01 04:30:00
2016-01-01 05:00:00
2016-01-01 05:30:00
2016-01-01 06:00:00
2016-01-01 06:30:00
2016-01-01 07:00:00
2016-01-01 07:30:00
2016-01-01 08:00:00
2016-01-01 08:30:00
2016-01-01 09:00:00
2016-01-01 09:30:00
2016-01-01 10:00:00
2016-01-01 10:30:00
2016-01-01 11:00:00
2016-01-01 11:30:00
2016-01-01 12:00:00
2016-01-01 12:30:00
2016-01-01 13:00:00
2016-01-01 13:30:00
2016-01-01 14:00:00
2016-01-01 14:30:00
2016-01-01 15:00:00
2016-01-01 15:30:00
2016-01-01 16:00:00
2016-01-01 16:30:00
2016-01-01 17:00:00
2016-01-01 17:30:00
2016-01-01 18:00:00
2016-01-01 18:30:00
2016-01-01 19:00:00
2016-01-01 19:30:00
2016-01-01 20:00:00
2016-01-01 20:30:00
2016-01-01 21:00:00
2016-01-01 21:30:00
2016-01-01 22:00:00
2016-01-01 22:30:00
2016-01-01 23:00:00
2016-01-01 23:30:00
2016-01-02 00:00:00
2016-01-02 00:30:00
This is a very large array containing time stamp for every half hour interval for 2 year duration. I wanted to extract the year (say 2016), day (say 1), month (say 1), and time (say 00:30 as 0.5) from this table data. How to do the same? Kindly help me.
0 Comments
Answers (2)
VBBV
on 19 Dec 2022
Edited: VBBV
on 19 Dec 2022
A = string({'2016-01-09 00:30:00';'2017-05-10 01:00:00'});
At = table(A,'VariableNames',{'Time'});
for k = 1:length(At.Time)
Y(k) = datetime(At.Time(k),'Format','yyyy'); % year
M(k) = datetime(At.Time(k),'Format','MM'); % month
D(k) = datetime(At.Time(k),'Format','dd'); % day
H(k) = datetime(At.Time(k),'Format','hh:mm'); % time
end
Y, M, D , H
1 Comment
Stephen23
on 19 Dec 2022
Edited: Stephen23
on 19 Dec 2022
This code simply changes the formatting, but the underlying date/time data is still stored in the DATETIME object. So it does not actually "extract the year ... day .. month ... and time ... from this table data", it just changes how the DATETIME object is displayed.
Stephen23
on 19 Dec 2022
Edited: Stephen23
on 19 Dec 2022
The MATLAB approach is to use YMD() and TIMEOFDAY() and HOURS():
S = ["2016-01-01 00:30:00"; "2016-01-01 01:00:00"; "2016-01-01 01:30:00"; "2016-01-01 02:00:00"; "2016-01-01 02:30:00"; "2016-01-01 03:00:00"; "2016-01-01 03:30:00"];
T = datetime(S)
[Y,M,D] = ymd(T)
H = hours(timeofday(T))
0 Comments
See Also
Categories
Find more on Dates and Time in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!