Problem in using datetime

4 vues (au cours des 30 derniers jours)
Agnivo Gosai
Agnivo Gosai le 6 Août 2021
Commenté : Agnivo Gosai le 6 Août 2021
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 commentaires
Sebastiano Marinelli
Sebastiano Marinelli le 6 Août 2021
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
Agnivo Gosai
Agnivo Gosai le 6 Août 2021
Thanks, this works

Connectez-vous pour commenter.

Réponse acceptée

Dave B
Dave B le 6 Août 2021
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.

Plus de réponses (0)

Catégories

En savoir plus sur Data Type Conversion dans Help Center et File Exchange

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by