MATLAB Answers

How can I convert data format from "datetime" to "year&num" format?

3 views (last 30 days)
It might be easy question,
I have a time series components with variable name "x". eg) 1962-01-02 00:00:00.
How can I convert this format to "196201"? (yyyyww).
I tried use year(x), week(x), but it is difficult to build above "yyyyww" format as I wanted.
Thanks :)


Sign in to comment.

Accepted Answer

Shunichi Kusano
Shunichi Kusano on 16 Aug 2019
Hi, jee.
"w" must be in uppercase, "W".
This is a sample code.
x(1) = datetime("1984-03-02 00:00:00");
x(2) = datetime("2019-08-16 01:01:01");
datetime(year(x), month(x), day(x), 'Format', 'yyyyWW')
hope this helps.


Steven Lord
Steven Lord on 16 Aug 2019
You don't need to create a new datetime to change the Format. Just set the Format property of the existing datetime.
>> x(1) = datetime("1984-03-02 00:00:00");
>> x(2) = datetime("2019-08-16 01:01:01");
>> x.Format = 'yyyyWW'
x =
1×2 datetime array
198401 201903
If you created a new datetime to trim the hour, minute, and second data so each represents midnight on its date, you can do that with dateshift. I changed x's Format back to the default first. I'm creating a new datetime array solely so you can compare before shifting and after shifting.
>> x.Format = 'default';
>> y = dateshift(x, 'start', 'day')
y =
1×2 datetime array
02-Mar-1984 00:00:00 16-Aug-2019 00:00:00

Sign in to comment.

More Answers (0)

Sign in to answer this question.