Convert date string to Date number error

25 次查看(过去 30 天)
Good morning,
Little stuck on this. Using Matlab 2015b and looking at converting this date string into a datenumber using datenum.
The date string im trying to convert is:
2015-05-31 14:52:27.420
What im using:
op_datetime = '2015-05-31 14:52:27.420'
format = 'yyyy-mm-dd HH:MM:SS.Z'
datenum(op_datetime, format)
This gives me the following error:
Error using datenum (line178)
DATENUM failed.
Caused by:
Error using dtstr2dtnummx
Failed on converting date string to date number.
The internal date time format that Matlab gives is:
I have tried changing the split seconds into a different format ie.
format = yyyy-mm-dd HH:MM:SS.SSS
But this gives me an error saying:
Error using datenum(linie178)
DATENUM failed.
Caused by:
Error using matlab.internal.datetime.cnv2icudf (line 137)
Unrecognized second format. Format string: yyyy-mm-dd HH:MM:SS.SSS
So have tried other formats and different ways but cant get anything to work. Is this due to the split seconds format?
Any help is appreciated.
Thank you.

回答(1 个)

Stephen23
Stephen23 2016-2-18
编辑:Stephen23 2016-2-19
When you read the datenum documentation you will find that the correct millisecond token is FFF:
yyyy-mm-dd HH:MM:SS.FFF
for example:
>> op_datetime = '2015-05-31 14:52:27.420';
>> datenum(op_datetime,'yyyy-mm-dd HH:MM:SS.FFF')
ans =
7.3612e+05
  3 个评论
Peter Perkins
Peter Perkins 2016-2-18
编辑:Stephen23 2016-2-18
Does this not work for you?
>> datenum('2015-05-31 14:52:27.420','yyyy-mm-dd HH:MM:SS.FFF')
ans =
7.3612e+05
If you're in R2015b, you should consider using datetime, and moving away from datenum and datestr.
Stephen23
Stephen23 2016-2-18
@Dan Howard: It is possible that there might be some characters in the string that are causing this. Control characters and other unprintable characters sometimes get read from files or other data sources, are very difficult to spot.
You should test the code that I gave (and that Peter Perkins used) with the string from the question, not using any other data source. You should get the same result as we did.
Secondly, please tell us exactly what is output from this command:
double(op_datetime)

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Dates and Time 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by