MATLAB Answers

0

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

Asked by jee young yoo on 16 Aug 2019
Latest activity Commented on by Steven Lord
on 16 Aug 2019
Hi,
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 :)

  0 Comments

Sign in to comment.

Products


Release

R2019a

1 Answer

Answer by Shunichi Kusano on 16 Aug 2019
 Accepted Answer

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.

  2 Comments

Thanks for your kind explanation..!
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.