How to convert Data from 'yyyyMMddhhmm' format to datetime format

23 次查看(过去 30 天)
Hello
I have been searching for a solution to converting my data from a number value with a 'yyyyMMddhhmm' format to a datetime format. Previously i attempted the following:
dtm = datetime(HS_Date,'InputFormat','yyyyMMddHHmm');
where HS_date is a matrix of 1x52561 double values, the data is from 202201010000 to 202301010000.
But i get an error message saying the following: "Error using Datetime (line 588) 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."
The ConvertFrom parameter only offers the yyyMMdd format and is not an viable option.
I am unsure if i am defining anything wrongly, or if i need to format my data differently to make the function work.
note: my data is showcased in the program as 202201010000.000, but i cannot change or remove the decimals using the round or fix function.
Kind regards

采纳的回答

Stephen23
Stephen23 2021-11-9
编辑:Stephen23 2021-11-9
"... HS_date is a matrix of 1x52561 double values, the data is from 202201010000 to 202301010000."
Abuse of decimal numbers to represent date/time values in entirely different bases that coincidentally happen to have the same digits... ugh, Ugh, UGH. The best solution would be to store/import that data correctly.
But that unnatural data can be converted to DATETIME with a little bit of effort:
N = [202201010000;202301010000]; % very badly designed data.
D = datetime(compose("%d",N),'InputFormat','yyyyMMddHHmm')
D = 2×1 datetime array
01-Jan-2022 01-Jan-2023
If you only need to date part then you could use the inbuilt ConvertFrom:
D = datetime(N/1e4,'ConvertFrom','yyyymmdd')
D = 2×1 datetime array
01-Jan-2022 01-Jan-2023

更多回答(1 个)

Chunru
Chunru 2021-11-9
dstr = ["202201010000.000" "202301010000.000"]
dstr = 1×2 string array
"202201010000.000" "202301010000.000"
t = datetime(dstr,'InputFormat','yyyyMMddHHmm.SSS')
t = 1×2 datetime array
01-Jan-2022 01-Jan-2023

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by