How to convert a string into a date or datenum?

I have a column, about [4000 x 1] with the format 'yyyymmddHH'. Yes, all the numbers are together.
And i need to get a date, or a datenum from that, but i cant, since functions like datetime need the numbers separated.
Anyone know how to get arround this?
Thank you.

回答 (1 件)

Stephen23
Stephen23 2021 年 6 月 17 日
編集済み: Stephen23 2021 年 6 月 17 日

1 投票

"... but i cant, since functions like datetime need the numbers separated."
I don't see that restriction mentioned anywhere in the DATETIME documentation.
S = ["2021061701";"2021010100";"1913061423"]
S = 3×1 string array
"2021061701" "2021010100" "1913061423"
D = datetime(S, 'InputFormat','yyyyMMddHH')
D = 3×1 datetime array
17-Jun-2021 01:00:00 01-Jan-2021 00:00:00 14-Jun-1913 23:00:00

6 件のコメント

Bruno Carvalho
Bruno Carvalho 2021 年 6 月 17 日
Mine gives me error.
"Error using datetime (line 597)
Numeric input data must be a matrix with three or six columns, or else three, six, or seven separate numeric
arrays. You can also create datetimes from a single numeric array using the 'ConvertFrom' parameter."
Stephen23
Stephen23 2021 年 6 月 17 日
編集済み: Stephen23 2021 年 6 月 17 日
If the data are stored as numeric where the digits of one value represent date units (ugh, ugh, ugh, a true abomination and crime against nature) then you can convert to string first:
VeryBadlyStoredDates = [2021061701;2021010100;1913061423] % should be illegal
VeryBadlyStoredDates = 3×1
2021061701 2021010100 1913061423
DT = datetime(string(VeryBadlyStoredDates), 'InputFormat','yyyyMMddHH')
DT = 3×1 datetime array
17-Jun-2021 01:00:00 01-Jan-2021 00:00:00 14-Jun-1913 23:00:00
Even better: create or import that data properly as datetime, rather than as numeric.
Steven Lord
Steven Lord 2021 年 6 月 17 日
If you have to operate on the numbers, datetime can handle most of the conversion. You just have to handle the hour data.
VeryBadlyStoredDates = [2021061701;2021010100;1913061423]; % should be illegal
hourData = mod(VeryBadlyStoredDates, 100)
hourData = 3×1
1 0 23
yyyyMMdd = (VeryBadlyStoredDates-hourData)./100
yyyyMMdd = 3×1
20210617 20210101 19130614
DT = datetime(yyyyMMdd, 'ConvertFrom', 'yyyymmdd') + hours(hourData)
DT = 3×1 datetime array
17-Jun-2021 01:00:00 01-Jan-2021 00:00:00 14-Jun-1913 23:00:00
Bruno Carvalho
Bruno Carvalho 2021 年 6 月 18 日
Converting it into a string worked!!
Thank you so much. And i totally agree, storing dates like this just gave me more work for nothing...
Bruno Carvalho
Bruno Carvalho 2021 年 6 月 18 日
If you can, answer again in a seperate answer so i can accept your answer
Stephen23
Stephen23 2021 年 6 月 18 日
@Bruno Carvalho: you can accept this answer, if one of the comments includes the solution.

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

カテゴリ

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

質問済み:

2021 年 6 月 17 日

コメント済み:

2021 年 6 月 18 日

Community Treasure Hunt

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

Start Hunting!

Translated by