Hi guys,
I have read in a column of dates and times from an excel document using xlsread and now have a cell of dates in the form 'yyyy-mm-dd hh:mm:ss AM/PM'.
I would like to extract from this cell a vector with the time in the form hhmm. How might I go about doing this?
Thanks,
Justin

 채택된 답변

Star Strider
Star Strider 2015년 2월 11일

0 개 추천

See datenum, datestr and their friends.

댓글 수: 5

Justin Duval
Justin Duval 2015년 2월 11일
Thanks for the quick answer. I have successfully used datestr to put the date and time data into the form dd-mm-yyyy hh:ss:mm as a char element.
I am now having difficulty using datenum to get me any further. My data is in 15 minute increments where the time is more important than the date. Is there a way that I can now extract just the time from my char element in the form hhmm so that I may use it in my code going forward?
You simply have to remember that upper-case letters indicate time fields and lower-case letters date fields.
Example:
dt = {'2014-02-10 10:15:27 PM'}; % Original Date
dn = datenum(dt, 'yyyy-mm-dd HH:MM:SS AM'); % Date Number
ts = datestr(dn, 'HHMM') % Desired Time Format
produces:
ts =
2215
You also have to specify 'AM' or 'PM' (it doesn’t matter which) in the appropriate field if you have times designated as such. MATLAB will do the conversion automatically. (Here it converted 10 PM correctly as 22 in the ‘ts’ assignment.
Justin Duval
Justin Duval 2015년 2월 11일
YES! That worked great, and you're right, my problem was forgetting that I needed to use upper-case letters to indicate time fields.
Thanks very much for your help.
Justin
Justin Duval
Justin Duval 2015년 2월 11일
편집: Justin Duval 2015년 2월 11일
Of course I've come across another obstacle. I now have my time data in the HHMM form I need it in, but as a char. Is it possible to convert this vector of char data into a vector of numerical data?
EDIT: Scratch that. I converted the character array to a cell array using cellstr, and converted that to a numerical vector using str2double.
IF there is a smarter way to do this, please let me know. Thanks again for your help!
Justin
My pleasure!
If you want the date fields as numeric, use the datevec function:
dt = {'2014-02-10 10:15:27 PM'}; % Original Date
dn = datenum(dt, 'yyyy-mm-dd HH:MM:SS AM'); % Date Number
tv = datevec(dn); % Date Vector
hhmm = tv(:,4:5) % Get Hour & Minute Fields
produces:
hhmm =
22 15

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Dates and Time에 대해 자세히 알아보기

질문:

2015년 2월 11일

댓글:

2015년 2월 11일

Community Treasure Hunt

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

Start Hunting!

Translated by