Problem in using datetime

4 次查看(过去 30 天)
Hi, I have timestamp in the form of strings, for e.g.
e =
1×1 cell array
{'8-3-2021 9-03-51 PM'}
However, when I use the following code to comvert it into "datetime" format, I end up with this :
new1 = datetime(e, 'InputFormat', 'M-d-yyyy H-mm-ss a', 'Format', 'yyyy-M-d H-mm-ss a');
new1(isnat(new1)) = datetime(e(isnat(new1)), 'InputFormat', 'M-d-yyyy H-mm-ss a');
I also get the warning :
Warning: The format 'M-d-yyyy H-mm-ss a' contains fields for 24 hour of day (H) and for day period (a). This will cause unexpected results when converting from text. See the
datetime.Format property for a complete description of the identifiers used in datetime formats.
>> new1
new1 =
datetime
2021-8-3 12-03-51 PM
I tried different things but could not fix it.
I don't quite understand why the time changes to 12 at the hour position from the original 9.
Any help is much appreciated.
  2 个评论
Sebastiano Marinelli
I think the problem is in using the capital "h" try this code should work:
e = {'8-3-2021 9-03-51 PM'};
new1 = datetime(e, 'InputFormat', 'M-d-yyyy h-mm-ss a', 'Format', 'yyyy-M-d h-mm-ss a');
new1(isnat(new1)) = datetime(e(isnat(new1)), 'InputFormat', 'M-d-yyyy h-mm-ss a');
Proably using the capital H means that you use the 24h format not the 12 format. Let me know if it works

请先登录,再进行评论。

采纳的回答

Dave B
Dave B 2021-8-6
The H in your format is referring to a 24-hour clock hour, as in 14 to represent 2pm, but that doesn't make sense as you're also specifying "PM". I suspect you need to change this to a lowercase h.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by