Convert Excel String time to number

조회 수: 2 (최근 30일)
matlabuser12
matlabuser12 2014년 10월 30일
댓글: matlabuser12 2014년 10월 30일
My excel spreadsheet that I am reading into matlab with xlsread has text for the time in the format of 11:23:23 AM for example. this is a string with no date associated with it so when I try and run datenum or datevec I get an error Failed to lookup month of year. I also tried str2double but that just gives me a series of NaN . What am I looking to do? I need to convert a series of times in an array and then compute the elapsed time among other things.

답변 (2개)

Ken Atwell
Ken Atwell 2014년 10월 30일
This is not pretty, but you can split the string on the ':' and compute the number of seconds since midnight. The code below used cellfun to vectorize the code; a for loop could be use and might be easier to understand (but likely sacrificing performance).
testData = repmat({'11:23:23'}, [10,1]);
hms = cellfun(@(x) str2double(strsplit(x, ':')), testData, 'UniformOutput', 0);
cellfun(@(x) x(1)*60*60+x(2)*60+x(3), hms)
You can compute duration so long as events don't cross midnight. If events do cross midnight, things become more complicate. In that case, if you have R2014b, the new datetime/duration functions may be useful. Here is a intro video.
  댓글 수: 1
matlabuser12
matlabuser12 2014년 10월 30일
I only have 2012, but luckily they run from 7am until 5pm so no worries there. the time however is not recorded in 24hr format but 12hr. I will give this a try, thanks!

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


Stalin Samuel
Stalin Samuel 2014년 10월 30일
  댓글 수: 1
matlabuser12
matlabuser12 2014년 10월 30일
it doesnt work, also returns just NaN

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

카테고리

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