Azzera filtri
Azzera filtri

How do I convert seconds since specific yyyy-mm-dd HH:MM:SS into date string?

22 visualizzazioni (ultimi 30 giorni)
I am extracting some parameters from a NetCDF file for use with some other software.
The time data is given as seconds since 2012-03-01 00:00:00 +00:00 in increments of 1200 seconds.
How do I create a variable containing date time data as yyyy-mm-dd HH:MM:SS? (the format required by the other software I am using)
I have tried:
DateTime=datestr(t+datenum(2012,03,01,0,0,0))
The output i get is wildly wrong, advancing in increments of approx. 3-4 years rather than increments of 20 minutes.
I plan to use this time data as a column in a CSV file.
I am completely new to Matlab prior to starting this project so if what i am doing doesnt make sense i apologise and appreciate any and all pointers!

Risposta accettata

the cyclist
the cyclist il 20 Ago 2021
Modificato: the cyclist il 20 Ago 2021
t = [0 1200];
convertedDateTime = datetime(2012,03,01,0,0,t)
convertedDateTime = 1×2 datetime array
01-Mar-2012 00:00:00 01-Mar-2012 00:20:00
The output will be in the datetime array format, which is the canonical method to store times in MATLAB. (There are many older ones as well, but this is best.)
  3 Commenti
the cyclist
the cyclist il 20 Ago 2021
Happy to help. Just as an FYI, your original method would have worked, but the datenum is a count of days, so to correctly add an array measured in seconds to it, you needed
t = [0 1200];
dt=datestr(t/86400+datenum(2012,03,01,0,0,0))
dt = 2×20 char array
'01-Mar-2012 00:00:00' '01-Mar-2012 00:20:00'
because there are 86,400 seconds in a day. However, the resulting character array (or even just the datenum format) is not as well suited to future calculations. It is much better, to use the canonical format, and learn the associated functions for handling datetime values.
Steven Lord
Steven Lord il 20 Ago 2021
Another way to do this that may be more intuitive to read is to use datetime and duration arithmetic:
baseTime = datetime(2012, 3, 1);
convertedTime = baseTime + seconds([0 1200])
convertedTime = 1×2 datetime array
01-Mar-2012 00:00:00 01-Mar-2012 00:20:00
That second line clearly is adding some number of seconds to baseTime.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Dates and Time in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by