Convert string into datetime

90 views (last 30 days)
Madison
Madison on 1 Nov 2024 at 10:01
Edited: Umar on 2 Nov 2024 at 3:12
I have a data set with a year worth of data that has downloaded as string and I am unsure how to convert this to datetime so that I can plot it against other variables. I think this is the reason I can't plot my data against other variables because when I try to, I get the error message 'error using plot' 'invalid data arguement'.

Answers (3)

Mohammad Sami
Mohammad Sami on 1 Nov 2024 at 10:12
you can simply use the datetime function to convert a string into datetime type
dt_string = ["2023-10-31 01:02:03" "2023-11-01 05:06:07"];
datetime(dt_string)
ans = 1x2 datetime array
31-Oct-2023 01:02:03 01-Nov-2023 05:06:07
% if the default input format is not suitable you can specify it
dt = datetime(dt_string,"InputFormat","uuuu-MM-dd HH:mm:ss")
dt = 1x2 datetime array
31-Oct-2023 01:02:03 01-Nov-2023 05:06:07
plot(dt,[5 6])

Star Strider
Star Strider on 1 Nov 2024 at 10:14
It would help to have the file.
Try this —
Date_Time_rural = ["2023-10-31 00:00:00"; "2023-11-01 00:00:00"; "2023-11-02 00:00:00"]
Date_Time_rural = 3x1 string array
"2023-10-31 00:00:00" "2023-11-01 00:00:00" "2023-11-02 00:00:00"
Date_Time_rural_dt = datetime(Date_Time_rural,InputFormat="yyyy-MM-dd HH:mm:ss")
Date_Time_rural_dt = 3x1 datetime array
31-Oct-2023 01-Nov-2023 02-Nov-2023
You could also specify an OutputFormat that includes the time, however since it is uniformaly midnight in these, that is likely not necessary.
.

Umar
Umar on 1 Nov 2024 at 10:57
Edited: Umar on 2 Nov 2024 at 3:12

Hi @Madison,

To resolve the issue of plotting your data against datetime variables in MATLAB, it is essential to convert the string representations of dates into MATLAB's datetime format. This conversion allows for proper handling of date and time data, enabling you to plot it against other numerical variables without encountering errors. First, ensure that your data is loaded correctly. You mentioned that you have a dataset with string dates. For demonstration purposes, I will create synthetic data that mimics your structure. Use the datetime function to convert the string array to a datetime array. This function allows you to specify the format of the date strings. Once the conversion is complete, you can plot the data using the plot function. Here is a complete example that includes synthetic data creation, conversion of string dates to datetime, and plotting:

% Step 1: Create synthetic data
% Simulating a year of daily data
numDays = 361; % Number of days
dateStrings = strings(numDays, 1); % Preallocate string array
% Generate date strings for the year 2023
for i = 1:numDays
  dateStrings(i) = datestr(datetime(2023, 10, 31) + days(i-1),   
 'yyyy-mm-dd HH:MM:SS');
end
% Simulating some random data for plotting
Average_rural = rand(numDays, 1) * 100; % Random data for rural 
average
% Step 2: Convert string dates to datetime
DateTime_rural = datetime(dateStrings, 'InputFormat', 'yyyy-MM-dd 
 HH:mm:ss');
% Step 3: Plotting the data
figure; % Create a new figure
plot(DateTime_rural, Average_rural, 'b-', 'LineWidth', 1.5);
%   Plotting
xlabel('Date'); % X-axis label
ylabel('Average Rural Data'); % Y-axis label
title('Average Rural Data Over Time'); % Title
grid on; % Add grid for better readability

Please see attached.

For more information or guidance regarding datetime function, please refer to

datetime

Here is alternative version since mathworks document mentions that 2022b does not recommend to use datestr.

% Sample data for date strings
dateStrings = {'2023-01-01', '2023-01-02', '2023-01-03'};
% Convert to datetime using the specified input format
dateTimes = datetime(dateStrings, 'InputFormat', 'yyyy-MM-dd'); 

Note: Here, the datetime function is utilized to convert the string representations of dates into MATLAB's datetime format. The InputFormat parameter specifies the expected format of the input strings, ensuring accurate conversion.

% Display the result of the datetime conversion
disp(dateTimes);
% Sample data for plotting corresponding to the dates
values = [10, 15, 20];
% Create a figure for plotting
figure;
% Plotting the values against the datetime objects
plot(dateTimes, values, '-o');
% Labeling the x-axis
xlabel('Date');
% Labeling the y-axis
ylabel('Values');
% Adding a title to the plot
title('Plot of Values Over Time');
% Enabling the grid for better readability
grid on;

Please see attached.

By following the steps outlined above, you should be able to convert your string date data into a format suitable for plotting in MATLAB. This will eliminate the errors you encountered and allow for effective visualization of your data. If you have any further questions or need additional assistance, feel free to ask!

  2 Comments
Stephen23
Stephen23 on 1 Nov 2024 at 11:11
Edited: Stephen23 on 1 Nov 2024 at 11:11
Note that DATESTR is deprecated:
Much better to use DATETIME to create the fake data. But apparently AI training does not keep up-to-date with the documentation.
Umar
Umar on 2 Nov 2024 at 2:21
Hi @Stephen23, please pay close attention to my comments I did mention to use datetime.

Sign in to comment.

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!