How to convert the number of seconds from an epoch into UTC using the datetime function.
조회 수: 155 (최근 30일)
이전 댓글 표시
I am struggling to convert the number of seconds from an epoch (1980-01-06 GPS epoch) into UTC using the datetime function. The following commands give me a time of 18-Mar-2021 20:37:31, however in UTC this should be 18-Mar-2021 20:37:13 since I would need to subtract out the number of leap seconds from the total (currently there are 18 leap seconds since the 1980-01-06 GPS epoch).
NoOfSeconds=1300135051;
datetime(NoOfSeconds,'convertfrom','epochtime','Epoch','1980-01-06')
Can the datetime function automatically account for leapseconds in this conversion? I tried using the 'TimeZone','UTCLeapSeconds' name/value pair, but this adds 18 seconds since it assumes the time is already in UTC.
댓글 수: 0
채택된 답변
Peter Perkins
2021년 8월 2일
Matthew, this is easier than you think. In MATLAB, 'TimeZone','UTC' is sort of a ficticious timeline that pretends that leaps seconds don't exist (because hardly anyone wants to actually account for leap seconds). 'UTCLeapSeconds' is the timeline that knows all about leap seconds. The GPS timeline (in the real world) ticks off the same leap seconds as 'UTCLeapSeconds' in MATLAB does, it just doesn't treat them specially. So for the purposes of arithmetic, i.e. elapsed time, 'UTCLeapSeconds' is what you want. Then all you have to do is change to 'UTC' (or not, it's up to you).
>> epoch = datetime(1980,1,6,'TimeZone','UTCLeapSeconds')
epoch =
datetime
1980-01-06T00:00:00.000Z
>> dtUTC = epoch + seconds(1300135051)
dtUTC =
datetime
2021-03-18T20:37:13.000Z
>> dtUTC.TimeZone = 'UTC'
dtUTC =
datetime
18-Mar-2021 20:37:13
Also, this Answer might be helpful:
If I may ask, I would be interested in hearing more about how you work with GPS timestamps. Do you always get "seconds since 1980" as your input? Do you need to work with "week number, seconds within week"? Do you need to work with "human readable timestamps" (e.g. 18-Mar-2021 20:37:31) that refer to the GPS timeline (as opposed to UTC)? Do you need to convert back to one of those GPS time formats? Thanks in advance for anything you are able to share.
댓글 수: 5
Peter Perkins
2022년 6월 20일
I imagine what you mean is convert GPS week/second to UTC. It would be good for you to be clear.
The GPS timeline has no leap seconds or DST, so each week is equal length. Convert to seconds, and then do what's described earlier in this thread.
추가 답변 (2개)
Sarthak
2024년 3월 13일
function date = gps2utc(g0, g1)
date = datevec(datetime(g0*604800+g1,'convertfrom','epochtime','Epoch','1980-01-06'));
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Dates and Time에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!