How to convert datetime to datestr including day of year

조회 수: 8 (최근 30일)
Kurt
Kurt 2022년 10월 25일
댓글: Kurt 2022년 10월 25일
I can convert a date string to a datetime object using datetime(), and convert that object back to a string using datestr(). However, my date includes a three-digit day of year field (day 179, say). I can use formatting to convert the day of year to the correct datetime object by overloading the day of month field, but I see no good way to reverse the process in datestr.
time_string = '22179114244.580';
date_time = datetime(time_string, 'InputFormat', 'uuDDDHHmmss.SSS')
date_time =
datetime 28-Jun-0022 11:42:44 % this is correct so far
formatOut = 'yy:ddd:HH:mm:SS.FFF';
datestr(date_time,formatOut)
ans =
'22:Tue:11:06:44.580' % WRONG
What format must I use to represent the day of year using datestr? Python uses %j to specifically represent the day of year, but I see no equivalent in Matlab.

채택된 답변

Steven Lord
Steven Lord 2022년 10월 25일
Looking at the table of format identifiers in the description of the Format property of datetime objects on the datetime documentation page, the identifiers D, DD, or DDD will do what you want if you convert the datetime into a string using string. You will also need to use s or ss for whole seconds and S, SS, etc. for fractional seconds.
time_string = '22179114244.580';
date_time = datetime(time_string, 'InputFormat', 'uuDDDHHmmss.SSS')
date_time = datetime
28-Jun-0022 11:42:44
formatOut = 'yy:D:HH:mm:ss.SSS';
s = string(date_time, formatOut)
s = "22:179:11:42:44.580"
Let's check.
day(date_time, 'dayofyear')
ans = 179
Wikipedia confirms that June 28th is the 179th (or 180th in a leap year) day of the year.
  댓글 수: 3
Steven Lord
Steven Lord 2022년 10월 25일
That's pretty easy. I'm going to use 6 second increments to make it easier to see the effect, but you could use 0.6 second increments.
N = datetime('now')
N = datetime
25-Oct-2022 19:23:08
sixSecondIncrements = N + seconds(0:6:30).'
sixSecondIncrements = 6×1 datetime array
25-Oct-2022 19:23:08 25-Oct-2022 19:23:14 25-Oct-2022 19:23:20 25-Oct-2022 19:23:26 25-Oct-2022 19:23:32 25-Oct-2022 19:23:38
Kurt
Kurt 2022년 10월 25일
That's exactly how I did it, except my increments are 0.6 seconds. Works great.

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by