Datetime won't recognise some cells

1 view (last 30 days)
I have a series of datetimes in the format 'HH:mm:ss.sss'. I am using the following code to convert from string into datetimes.
data.TimeofDay = datetime(data.TimeofDay,'Format','HH:mm:ss.sss')
Unable to resolve the name 'data.TimeofDay'.
In the attached .mat file, it contains the data file before and after the command above. For some reason, different values in the column are returned as NaT despite all rows seemingly being in the same format.
  1 Comment
the cyclist
the cyclist on 28 Jun 2022
Edited: the cyclist on 9 Jul 2022
Relevant for both your code and some of the answers:
  • 'Format' governs what the output looks like
  • 'InputFormat' governs what the input looks like
In your case, I believe MATLAB would have correctly inferred your input format, if had you left it unspecified:
datetime(data.TimeofDay)

Sign in to comment.

Accepted Answer

Cris LaPierre
Cris LaPierre on 28 Jun 2022
For miliseconds, you want to use a capital 'S'.
load datetime-problem.mat
datetime(databackup.TimeofDay,'Format','HH:mm:ss.sss')
ans = 14×1 datetime array
09:03:26.026 NaT NaT NaT NaT 09:10:47.047 NaT NaT NaT 09:16:15.015 NaT NaT NaT NaT
% corrected
datetime(databackup.TimeofDay,'Format','HH:mm:ss.SSS')
ans = 14×1 datetime array
09:03:32.026 09:05:04.939 09:06:32.609 09:07:58.886 09:09:23.436 09:10:48.047 09:12:12.351 09:13:42.538 09:15:07.079 09:16:41.015 09:36:12.951 09:37:52.603 09:39:16.163 09:40:41.993

More Answers (2)

the cyclist
the cyclist on 28 Jun 2022
Edited: the cyclist on 28 Jun 2022
Two minor but important changes to your syntax:
datetime(data.TimeofDay,'InputFormat','HH:mm:ss.SSS')
Note that I used
  • 'InputFormat' instead of 'Format'
  • .SSS instead of .sss

Voss
Voss on 28 Jun 2022
load datetime-problem.mat
databackup.TimeofDay
ans = 14×1 string array
"09:03:32.026" "09:05:04.939" "09:06:32.609" "09:07:58.886" "09:09:23.436" "09:10:48.047" "09:12:12.351" "09:13:42.538" "09:15:07.079" "09:16:41.015" "09:36:12.951" "09:37:52.603" "09:39:16.163" "09:40:41.993"
% original Format specification:
datetime(databackup.TimeofDay,'Format','HH:mm:ss.sss')
ans = 14×1 datetime array
09:03:26.026 NaT NaT NaT NaT 09:10:47.047 NaT NaT NaT 09:16:15.015 NaT NaT NaT NaT
% corrected Format specification:
datetime(databackup.TimeofDay,'Format','hh:mm:ss.SSS')
ans = 14×1 datetime array
09:03:32.026 09:05:04.939 09:06:32.609 09:07:58.886 09:09:23.436 09:10:48.047 09:12:12.351 09:13:42.538 09:15:07.079 09:16:41.015 09:36:12.951 09:37:52.603 09:39:16.163 09:40:41.993

Tags

Products


Release

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by