Skip to content

Instantly share code, notes, and snippets.

@adyork
Created April 19, 2022 20:49
Show Gist options
  • Save adyork/e2b1de46e19f2986a84deefd7f5ea897 to your computer and use it in GitHub Desktop.
Save adyork/e2b1de46e19f2986a84deefd7f5ea897 to your computer and use it in GitHub Desktop.
%% DateTime transformations
% goals:
% * add time zone to datetime
% * convert to ISO_DateTime_UTC
% * convert to ISO_DateTime_local
% * get epoch time (seconds since 1970)
% * check epoch conversion
%starting with a matlab datenum format (no time zone). But we know it is local (Mountain Time) timezone.
datenum = DATA.Time; %in this data structure DATA.Time is a time with seconds resolution (no time zone in datenum)
% 'MT' not a recognized timezone so looked at the avaialble ones with
% T = timezones('America')
% https://www.mathworks.com/help/thingspeak/time-zones-reference.html
% that says Mountain time is 'America/Denver' in that list
%make a datetime with time zone
datetime_MT = datetime(DATA.Time,'ConvertFrom','datenum','TimeZone','America/Denver');
%get string in ISO format without time zone in the string (is still mountain time)
ISO_DateTime_local=datestr(datetime_MT,'yyyy-mm-dd HH:MM');
% ISO_DateTime_local(end,:)
%
% ans =
%
% '2018-08-13 05:00'
% you can convert to UTC time by changing the .TimeZone of any datetime
% that has a timezone to 'Z' instead.
datetime_UTC = datetime_MT ; %making new variable, will convert in next step
datetime_UTC.TimeZone = 'Z'; % changes from whatever time zone it was to Z (UTC)
ISO_DateTime_UTC=datestr(datetime_UTC,'yyyy-mm-ddTHH:MMZ');
% ISO_DateTime_UTC(end,:)
%
% ans =
%
% '2018-08-13T11:00Z'
%Looks right since MT is UTC-6 in summer
% you can convert to epoch this way (example getting current time in epoch)
% int64(milliseconds(datetime('now','Timezone','UTC')-datetime('1970-01-01','Timezone','UTC')))
% can verify using https://www.epochconverter.com/
% convert to epoch (seconds since 1970 by taking the dataset's time (in
% UTC) "datetime_UTC" and subtracting time at 1970
unixtime = int64(seconds(datetime_UTC-datetime('1970-01-01','Timezone','UTC')));
disp('Start and End times in epoch and string')
disp([unixtime(1);unixtime(end)]);
disp([ISO_DateTime_UTC(1,:);ISO_DateTime_UTC(end,:)])
% results
% Start and End times in epoch and string
% 1532563200
% 1534158000
%
% 2018-07-26T00:00Z
% 2018-08-13T11:00Z
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment