Convert datetime to numeric - preserve date format

조회 수: 38 (최근 30일)
Elin Jacobs
Elin Jacobs 2023년 2월 27일
댓글: Campion Loong 2023년 3월 29일
I have a timetable with dates (datetime data type) in the format 'yyyy-MM-dd HH:mm'. I want to convert these to a numeric data type (double) but keeping the exact numbers of each date such that the datetime '2023-02-27 14:00' is converted to the double '202302271400'. The function yyyymmdd() allows me to do this for the date, but not the hour and minute, and none of the other built in functions to convert to datenumber seem to have this option. Thanks for any insights to this problem.

채택된 답변

Les Beckham
Les Beckham 2023년 2월 27일
편집: Les Beckham 2023년 2월 28일
Edited to work with datetime array vs a single datetime.
d = datetime(['2023-02-27 14:00'; '2023-02-27 15:00']) % test data - replace with your timetable
d = 2×1 datetime array
27-Feb-2023 14:00:00 27-Feb-2023 15:00:00
s = string(d, 'yyyyMMddHHmm')
s = 2×1 string array
"202302271400" "202302271500"
format long
% f = cellfun(@(s)sscanf(s, '%f'), s) % original method of converting to double
f = double(s) % An easier/cleaner method. Thanks to Walter for reminding me about this.
f = 2×1
1.0e+11 * 2.023022714000000 2.023022715000000
compose('%.0f', f)
ans = 2×1 cell array
{'202302271400'} {'202302271500'}
  댓글 수: 10
Elin Jacobs
Elin Jacobs 2023년 3월 29일
@Campion Loong You are right, I'm interfacing with a (poorly designed) database for a local weather station.
Campion Loong
Campion Loong 2023년 3월 29일
@Elin Jacobs Thanks for confirming. That (unfortunately) makes sense.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Dates and Time에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by