I have a CSV file with date and time values I want to import and convert to datetime

조회 수: 18 (최근 30일)
The import tool will not convert this to Datetime and I have tried many different options all of which will not allow me to convert the dates in this CSV file to datetime. Example of the format of the dates in the CSV file: {'1/1/2015 1:00:00 AM'} The format of the data is Month/Day/Year Hour:Min:Second AM or PM There are no "0"s infront of any of the month or day values. I have tried MM/DD/YYYY and many different versions of this format
Code that does not work:
DateStrings = importfile(:,'DateTime');
t = datetime(DateStrings,'InputFormat','M/d/y h:MM:SS a');
The clock values are a 12 hour clock as they start at just a date value and then the next value has the hour data and the AM/PM. Any help would be greatly appreciated!

채택된 답변

dpb
dpb 2016년 4월 5일
Use
t = datetime(DateStrings,'InputFormat','M/d/y h:mm:ss a');
instead. 'MM' --> Months and 'SS' --> fractional seconds fields. See <datetime-properties Format>
  댓글 수: 2
Tim Moriarty
Tim Moriarty 2016년 4월 5일
I used your code and this still comes up Error using datetime (line 613) Input data must be a numeric or a cell array or char matrix containing date/time strings. It is in a table as text '1/1/2015 1:00:00 AM'
dpb
dpb 2016년 4월 5일
Well, you didn't say that...extract the table column into a cell array or string array as instructed.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Kuifeng
Kuifeng 2016년 4월 5일
%After you have the strings of DateStrings, try the following
formatOut = 'dd mmm yyyy HH:MM:SS AM';
t=datestr(datenum(DateStrings,'dd/mm/yyyy HH:MM:SS',1900),formatOut)
  댓글 수: 1
Tim Moriarty
Tim Moriarty 2016년 4월 5일
The following works then I just have to join the two variables and put back to the origianl variable S = importfile{:,3}; DateStrings = S(:,1);
t = datetime(DateStrings,'InputFormat','M/d/y h:mm:ss a'); t1 = datetime(DateStrings,'InputFormat','M/d/y');

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Dates and Time에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by