datestr problem with minutes

Hello everyone,
I'm encountering a problem with date conversion. I have a dataset column with dates in '1/5/2017 12:10:00AM' form and I want to convert it into '2017-05-01 00:10:00' format. I used the datestr function but the minutes are incorrect. All rows return with 00 minutes.
How can I fix this?
Thank you in advance, Vanessa

3 件のコメント

Stephen23
Stephen23 2017 年 6 月 29 日
@Vanessa: please show us the code you have used and the data that causes this behavior.
Vanessa
Vanessa 2017 年 6 月 29 日
kwhm.date=datestr(kwhm.date,'yyyy-mm-dd HH:MM:SS');
date '1/5/2017 12:10:00AM' '1/5/2017 12:15:00AM' '1/5/2017 12:20:00AM' etc
Andrei Bobrov
Andrei Bobrov 2017 年 6 月 29 日
Dear Vanessa! please accept the answers that solved your problems.

サインインしてコメントする。

回答 (2 件)

Walter Roberson
Walter Roberson 2017 年 6 月 29 日

0 投票

t = datenum('1/5/2017 12:10:00AM' );
datestr(t, 'YYYY-mm-DD HH:MM:ss')
Andrei Bobrov
Andrei Bobrov 2017 年 6 月 29 日
編集済み: Andrei Bobrov 2017 年 6 月 29 日

0 投票

a = datetime('1/5/2017 12:10:00AM','I','dd/MM/yyyy hh:mm:ssa','F','yyyy-MM-dd HH:mm:ss')

4 件のコメント

Vanessa
Vanessa 2017 年 6 月 29 日
Thanks this worked but I have some rows which are '1/5/2017' without the time and the result of the above function is NaT. How can overcome this? thanks
Walter Roberson
Walter Roberson 2017 年 6 月 29 日
You cannot. When you use datetime() all of the entries need to be in the same 'InputFormat' (that here was abbreviated as 'I'). If you know you have entries that are in a different format, you need to detect and process them.
For example:
a = datetime(StringArrayOfTimes, 'I', 'dd/MM/yyyy hh:mm:ssa','F','yyyy-MM-dd HH:mm:ss');
failed_on = isnat(a);
a(failed_on) = datetime(StringArrayOfTimes(failed_on), 'I', 'dd/MM/yyyy', 'F', 'yyyy-MM-dd HH:mm:ss');
The above does a patch-up pass, where it tries to re-interpret the failed times with the abbreviated format.
Vanessa
Vanessa 2017 年 6 月 29 日
Thank you very much!!!
Andrei Bobrov
Andrei Bobrov 2017 年 6 月 29 日
a = {'1/5/2017';
'1/5/2017 12:10:00AM';
'1/5/2017 12:15:00AM';
'1/5/2017 12:20:00AM';
'2/5/2017'};
t = ~cellfun(@isempty,regexp(a,'\d{4}$'));
a(t) = cellfun(@(x)[x,' 00:00:00AM'],a(t),'un',0);
out = datetime(a,'I','dd/MM/yyyy hh:mm:ssa','F','yyyy-MM-dd HH:mm:ss')

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeDates and Time についてさらに検索

タグ

質問済み:

2017 年 6 月 29 日

コメント済み:

2017 年 6 月 29 日

Community Treasure Hunt

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

Start Hunting!

Translated by