Is there any fast way to truncate the time portion of a datetime array?

I have a datetime array t1 with datetime data eg('2017-05-04 15:20:21') is there a fast way to get rid of the time portion and change the whole array into datetime data with date only eg('2017-05-04')?
I've tried loop all and for each element in t1 element.hour = 0, element. minute=0 and element.second =0, i've also tried arrayfun(@(z)datetime(year(z),month(z),day(z)),MyDatetimeArray,'UniformOutput',false) but both seems to be pretty slow if the length of t1 is large and the second method gives cell array instead of datetime array.
Any smarter way of doing this guys?? Thanks a lot!!

Risposte (2)

d = dateshift(MyDatetimeArray, 'start', 'day');
d.Format = 'dd-MMM-yyyy';
Note: generally speaking when you are working with datetime objects, you should be keeping in mind their timezone. You then have to ask which start of day you want: do you want the start of day relative to the timezone the object is set to, or do you want the start of day relative to your local timezone? Right at the moment, the start of the day relative a time "now" expressed in UTC is about six hours ago even though start of day relative to "now" in my local timezone was about an hour ago.
Also note that it is not possible to have "pure date" datetime objects. You can have datetime objects that have been set to not display the time, but they have a time, even if that time is 00:00:00.0000 relative to the date.

4 Commenti

Thanks Walter, i get what you meant. In fact what i'm trying to do is that given 2 timeseries, t1 with minute level data eg('2017-01-01 15:00:00'), t2 with date level eg('2017-01-01'). I want to set the hour, minute and anything else to be zeros so that i'm left with something that i can match with t2 (like doing ismember then return some data given same date). Is there a fast way to change the time portion to 0s? Thanks a lot!!!
d = dateshift(MyDatetimeArray, 'start', 'day');
... and then (perhaps) d.Format = 'dd-MMM-yyy' or something similar.
Yup... that was the second line in my original response.

Accedi per commentare.

d = datetime({'19-Apr-2016 11:29:31'; '27-Apr-2016 00:05:59'; '31-Mar-2016 18:35:46'}) ;
d.Format = 'dd-MMM-yyyy';
column1 = cellstr(d) % Cell array of strings.
d.Format = 'hh:mm:ss';
column2 = cellstr(d) % Cell array of strings.

2 Commenti

Hi, please I want to convert the AM\PM time format to UT please, like the attachd image.
Could you help?
datetime('4:07:55 PM','Format', 'HH:mm:ss')
ans =
datetime
16:07:55

Accedi per commentare.

Tag

Richiesto:

il 3 Ago 2017

Commentato:

il 22 Dic 2019

Community Treasure Hunt

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

Start Hunting!

Translated by