Import timestamps with alternating date formats
7 views (last 30 days)
Show older comments
Chris Feist
on 21 Jun 2024
Commented: Stephen23
on 22 Jun 2024 at 18:14
Hello!
I have .csv data files that contain gps coordinates with timestamps. I want to import these data files into MATLAB. The problem I am having is the timestamp has an alternating date format, or at least matlab import is treating it as such. Timestamps look like:
Timestamp
16:15:29
16:15:29.500000
16:15:30
16:15:30.500000
etc.
Using import tool I can set a custom date format to HH:mm:ss.SSSSSS but this doesn't work for the timestamps that don't include the .SSSSSS
The import tool assigns NaT to those timestamps. Any ideas?
1 Comment
Accepted Answer
Star Strider
on 21 Jun 2024
It does not actually appear to be alternating, although the trailing zeros on some may indicate that the time is not exactly those values and instead something close to them (perhaps an additional
second).
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1720191/image.png)
This is a bit more convoluted than I’d like it to be, however itt has the virtue of working —
Timestamp = {'16:15:29'
'16:15:29.500000'
'16:15:30'
'16:15:30.500000'}
TimestampMtx = str2double(split(Timestamp,':')) % Convert To Numeric Array
Timestamps = compose('%2d:%2d:%4.1f',TimestampMtx) % Convert To Cell Array Of Strings
Timestamp2 = datetime(Timestamps, 'InputFormat','HH:mm:ss.S', 'Format','HH:mm:ss.S') % 'datetime' Array
.
More Answers (1)
Steven Lord
on 22 Jun 2024 at 16:50
A different approach is to convert all the data with the input format of the first entry in the list, then convert all the data that resulted in NaT values in the datetime array using a different input format or formats.
Timestamp = {'16:15:29'
'16:15:29.500000'
'16:15:30'
'16:15:30.500000'};
format1 = 'HH:mm:ss';
dt = datetime(Timestamp, InputFormat = format1, Format = format1)
This shows that entries 2 and 4 in Timestamp were not compatible with the input format in format1. So let's try converting those with a slightly different input format.
format2 = 'HH:mm:ss.SSSSSS';
dt(isnat(dt)) = datetime(Timestamp(isnat(dt)), InputFormat = format2)
To confirm that entries 2 and 4 in dt have the fractional seconds:
dt.Format = format2
If dt had still contained any NaT values I could have repeated this process with a third, fourth, etc. input format.
1 Comment
Stephen23
on 22 Jun 2024 at 18:14
This topic has come up a few times before. Perhaps a useful enhancement would be to let DATETIME's "InputFormat" value be a string array or cell array of chars, and which provides exactly this behavior.
See Also
Categories
Find more on Workspace Variables and MAT-Files 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!