String date and time identification
Show older comments
Hello, I have the following string:
date= '2021-07-011407404.5'
From here I would like to detect date and time in the following formar: 2021-07-01 14:07:40, the last number (e.g. 4.5) is another data and this number it can vary like 16.50, and so on.
Thank you for your support
Accepted Answer
More Answers (3)
Star Strider
on 5 Jan 2023
Edited: Star Strider
on 5 Jan 2023
If they all have the same format —
date= '2021-07-011407404.5'
DT = datetime(date(1:16), 'InputFormat','yyyy-MM-ddHHmmss', 'Format','yyyy-MM-dd HH:mm:ss')
LastNumber = str2double(date(17:end))
They must all have the same formats for this to work.
EDIT — (5 Jan 2023 at 18:28)
Added 'Format' name-value pair to datetime call.
.
1 Comment
Stephen23
on 5 Jan 2023
An alternative to indexing would be to use EXTRACTBEFORE(), which also works on string/cell of char arrays.
How consistent are is the information in your variable called date? Will they always look like what you have described in your question? You should consider renaming the variable from date to something that is not already a MATLAB function like DateValue.
DateValue = '2021-07-011407404.5';
NewDate = DateValue(1:10);
NewTime = [DateValue(11:12),':',DateValue(13:14),':',DateValue(15:16)];
RemainingInfo = str2double(DateValue(17:end));
%from here you can make them into formats MATLAB recognizes as datetime
DateTimeValue = datetime([NewDate,' ',NewTime]);
Hi,
Here is one of the possible ways of displaying the time strings:
DD= '2021-07-011407404.5';
DDate = DD(1:10)
D2 = DD(11:16);
DTime = strcat([D2(1:2) ':' D2(3:4) ':' D2(5:6)])
D3 = DD(17:end);
DTime2 = strcat([D3(1) '.' D3(end)])
ALL = ['Date: ' DDate ' Time: ' DTime ' Seconds: ' DTime2]
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!