KatyB
KatyB

Reputation: 3990

datetime format in matlab

I have some data that was given to me in excel and the time format is rather confusing. The fist column of the is the DateTime but with incorrect HH:MM and the second column is the correct hour of the day HH:MM:

time = {'01/01/2000 00:00',num2str(2300);
    '01/01/2000 00:00',num2str(2400);
    '01/01/2000 00:00',num2str(10);
    '01/01/2000 00:00',num2str(100)};

However, when the time exceeds midnight, instead of being 00:10 the time is 10, and 01:00 is 100. How could I alter these to the correct format? i.e. from the example above I would like the outcome to be:

time = {'01/01/2000 23:00';
    '01/01/2000 24:00';
    '01/01/2000 00:10';
    '01/01/2000 01:00'};

How could I achieve this?

Upvotes: 0

Views: 990

Answers (1)

im so confused
im so confused

Reputation: 2121

Using sprintf in MATLAB, you can use the field width specifier:

sprintf arguments

where

Field width: Minimum number of characters to print. Can be a number, or an asterisk (*) to refer to an argument in the input list. For example, the input list ('%12d', intmax) is equivalent to ('%*d', 12, intmax).

Thus your times should end up all looking like "XX:XX", with the leading zero added by the sprintf if it is missing and the colon added in.

Thanks to @Junuxx for the exact command: sprintf('%02i:%02i', hours, minutes)

To separate hours and minutes, you would obviously do time % 100 to get the minutes and integer divide by 100 to get the hours.

From there, you simply strcat or concatenate ["a" "b"] your two columns to get your desired result.

Upvotes: 3

Related Questions