convert from string to datetime in matlab

To convert a string to a datetime in MATLAB, you can use the datetime function. Here is an example:

main.m
str = '2021-09-14 09:30:00'; % input string in format 'yyyy-MM-dd HH:mm:ss'
dt = datetime(str); % convert string to datetime
125 chars
3 lines

In this example, the input string follows the format 'yyyy-MM-dd HH:mm:ss'. The datetime function can automatically parse the input string and create a datetime object.

If your input string has a different format, you can specify the format using the 'InputFormat' parameter of the datetime function. Here is an example:

main.m
str = '09/14/2021 09:30:00 AM'; % input string in format 'MM/dd/yyyy HH:mm:ss a'
fmt = 'MM/dd/yyyy HH:mm:ss a'; % format of the input string
dt = datetime(str, 'InputFormat', fmt); % convert string to datetime
210 chars
4 lines

In this example, the 'InputFormat' parameter is used to specify the format of the input string. The format string 'MM/dd/yyyy HH:mm:ss a' corresponds to the given input string.

Note that the datetime function returns a datetime object, which can be manipulated and formatted in various ways.

related categories

gistlibby LogSnag