How can I convert a string with fractional seconds into a datetime object?

14 views (last 30 days)
I have a string containing date and time in the following format:
date_string =
"1991-03-11 08:45:15.3"
I am not able to figure out how to specify the format. I have tried 'yyyy-MM-dd  HH:mm:SS' and 'yyyy-MM-dd  HH:mm:SSS' and various other combinations, but I keep getting this error:
ERROR: Error using datetime (line 616)
Unable to parse '1991-03-11 08:45:15.3' as a date/time using the format 'yyyy-MM-dd HH:mm:SS'.
How can I convert this string into a "datetime" object?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 26 Apr 2023
Edited: MathWorks Support Team on 26 Apr 2023
As per documentation, "datetime" format notation uses "s" for whole seconds, and "S" for fractional seconds. So to convert your dates to "datetime" you can run the following command:
>> mydate = datetime(date_string, 'InputFormat', 'yyyy-MM-dd HH:mm:ss.S')
mydate =
datetime
11-Mar-1991 08:45:15
  2 Comments
Steven Lord
Steven Lord on 18 Dec 2017
To include the fractional seconds in the display of the mydate variable, change its Format property.
mydate.Format = 'yyyy-MM-dd HH:mm:ss.S'
Peter Perkins
Peter Perkins on 19 Dec 2017
Or don't use the 'InputFormat parameter' when you create the datetime. Using 'Format' instead would be more appropriate here.

Sign in to comment.

More Answers (0)

Categories

Find more on Dates and Time in Help Center and File Exchange

Products


Release

R2016b

Community Treasure Hunt

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

Start Hunting!