Python/Django生成的Datetime字符串在Matlab 2018a解析异常求助
Hey there, let's break down why your datetime parsing is giving that wonky result—you've got two critical missteps in your code:
1. You're using Format instead of InputFormat
The Format parameter in MATLAB's datetime function controls how the datetime is displayed after parsing, not how the input string is interpreted. To tell MATLAB how to read your specific timestamp format, you need to use the InputFormat parameter instead.
2. Incorrect timezone offset format specifier
Your format string uses +HH:mm for the timezone offset, but MATLAB requires the XXX specifier to match ±HH:mm style offsets (like your +00:00). Using +HH:mm confuses MATLAB into treating the timezone part as part of the time itself, leading to the wrong hour/minute values.
Here's the corrected code:
% Your original Django timestamp datatime_str = '2020-08-18 16:48:13.722422+00:00'; % Define the correct input format (XXX handles the +00:00 offset) input_fmt = 'yyyy-MM-dd HH:mm:ss.SSSSSSXXX'; % Parse the timestamp using InputFormat (MATLAB will auto-detect the UTC offset from the string) dt = datetime(datatime_str, 'InputFormat', input_fmt); % Convert to your local timezone dt.TimeZone = 'local'; % Optional: Set your desired display format if needed dt.Format = 'yyyy-MM-dd HH:mm:ss.SSSSSSXXX';
What this does:
InputFormattells MATLAB exactly how to parse each part of your timestamp, including the microseconds (SSSSSS) and UTC offset (XXX).- Parsing first lets MATLAB recognize the original timestamp is in UTC (from
+00:00), then switchingTimeZonetolocalconverts it correctly to your local time. - The optional
Formatparameter ensures the output displays in the style you want.
Testing this:
If your local timezone is UTC+8, for example, you'll get a result like 2020-08-19 00:48:13.722422+08:00—which matches the expected conversion from the original UTC timestamp.
内容的提问来源于stack exchange,提问作者AJW

