Effacer les filtres
Effacer les filtres

How do I convert a string to a date?

462 vues (au cours des 30 derniers jours)
Joel Abrahams
Joel Abrahams le 17 Juil 2017
Currently I have the string:
2017-03-18 03:26:42.000000
I want to convert this to a date, and I use the following function:
datetime(my_string,'InputFormat','yyyy-mm-dd HH:MM:SS')
However, when I do this I get the following error:
Unable to parse '2017-03-18 03:26:42.000000' as a date/time using the format 'yyyy-mm-dd HH:MM:SS'.
I have also tried
datetime(my_string,'InputFormat','yyyy-mm-dd HH:MM:SSSSSSSSS')
and
datetime(my_string,'InputFormat','yyyy-mm-dd HH:MM:SS.SSSSSSS')
But none of these seem to work. How would I go about doing this?

Réponse acceptée

Guillaume
Guillaume le 17 Juil 2017
Modifié(e) : Guillaume le 17 Juil 2017
Carefully read the documentation of the Format property. The month identifier is uppercase M and the minute identifier is lowercase m. The seconds field is lowercase s with the fractional part as uppercase S. So:
datetime(my_string,'InputFormat','yyyy-MM-dd HH:mm:ss.S')
if you want to display the fractional seconds by default:
datetime(my_string,'InputFormat','yyyy-MM-dd HH:mm:ss.S', 'Format', 'yyyy-MM-dd HH:mm:ss.SSS')
  2 commentaires
Douglas Leaffer
Douglas Leaffer le 22 Jan 2022
The date and time vectors are the same length. I think perhaps the problem lies with the way the .txt file is imported. I have attached an excerpt of the file if you have bandwidth to suggest further help. The coumns of interest are date = column 7; time = column 8
Michael Connolly
Michael Connolly le 28 Mar 2023
Thank you for posting this! It fixed my problem.

Connectez-vous pour commenter.

Plus de réponses (1)

Rik
Rik le 17 Juil 2017
It is a bit confusing, but the capital S only denotes the fraction of a second, so not the second itself. The code below works.
my_string='2017-03-18 03:26:42.000000';
datetime(my_string,'InputFormat','yyyy-MM-dd HH:mm:ss.SSSSSS')
  5 commentaires
Amini
Amini le 3 Fév 2022
in this way it works:
DateStrings = {'24/09/2021:10:56:23'};
t = datetime(DateStrings,'InputFormat','dd/MM/yyyy:HH:mm:ss')
But my date is 24/Sep/2021:10:56:23
and in this way it doesn't work
DateStrings = {'24/Sep/2021:10:56:23'};
t = datetime(DateStrings,'InputFormat','dd/MM/yyyy:HH:mm:ss')
%again, beside the problem of two extra characters
Amini
Amini le 3 Fév 2022
I found it how to eliminate the extra characters, using erase but still stacked with MONTH part

Connectez-vous pour commenter.

Catégories

En savoir plus sur Dates and Time dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by