Clear Filters
Clear Filters

How to convert table variable to datetime and adjust timezone?

11 views (last 30 days)
Hi there! I have a table that reads a csv file for which column A is "Time" and is in posix-millisec format. I would like to convert the values to dd-mm-yyyy format and then convert values into the time zone which the data were taken. I would like these newly formatted versions of the values to replace the originals in my table. Here is what I have put together so far.
My Table is name "T":
The following line works fine and the resultant dates are at UTC time:
T.Time = datetime(T.Time,'ConvertFrom','epochtime','TicksPerSecond',1e3,'Format','dd-MMM-yyyy HH:mm:ss.SSS')
The following line appears to work, but I am not sure how to check, and I think tells Matlab that the table variable Time is in UTC timezone so that it can be converted with subsequent commands.
T.Time = datetime(T.Time, "TimeZone","UTC")
This is where I get lost: How can I convert all of the values in T.Time to be in 'America/New_York' timezone so that when I plot T.Time vs <Stuff> my time axis reads in New York time?
I tried the following but it throws an error "Error using . To assign to or create a variable in a table, the number of rows must match the height of the table."
T.Time = 'America/New_York'
Thank you!

Accepted Answer

Cris LaPierre
Cris LaPierre on 30 Apr 2024
I'm assuming the intial conversion to datetime is correct
Time = 1714509608*1e3; % milliseconds since 1/1/1970 0:00:00 UTC
T = table(Time);
T.Time = datetime(T.Time,'ConvertFrom','epochtime','TicksPerSecond',1e3,'Format','dd-MMM-yyyy HH:mm:ss.SSS')
T = table
Time ________________________ 30-Apr-2024 20:40:08.000
% Assign time zone
T.Time.TimeZone = "UTC"
T = table
Time ________________________ 30-Apr-2024 20:40:08.000
T.Time.TimeZone
ans = 'UTC'
% Convert to new Time Zone
T.Time.TimeZone = "America/New_York"
T = table
Time ________________________ 30-Apr-2024 16:40:08.000
T.Time.TimeZone
ans = 'America/New_York'
  2 Comments
Cris LaPierre
Cris LaPierre on 30 Apr 2024
You could simplify a little by specifying the time zone as a name-value pair in datetime
Time = 1714509608*1e3;
T = table(Time);
T.Time = datetime(T.Time,'ConvertFrom','epochtime','TicksPerSecond',1e3,'Format','dd-MMM-yyyy HH:mm:ss.SSS',...
TimeZone="UTC")
T = table
Time ________________________ 30-Apr-2024 20:40:08.000
% Check timezone
T.Time.TimeZone
ans = 'UTC'
% Now convert timezone
T.Time.TimeZone = "America/New_York"
T = table
Time ________________________ 30-Apr-2024 16:40:08.000
% Check timezone
T.Time.TimeZone
ans = 'America/New_York'

Sign in to comment.

More Answers (0)

Categories

Find more on Dates and Time in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!