Python datetime4[ns] to MATLAB

12 views (last 30 days)
Emily Browning
Emily Browning on 31 Oct 2022
Answered: Suvansh Arora on 3 Nov 2022
I'm trying to import data from an xarray in python with time data stored as (datetime64[ns]) into matlab by saving it as a netcdf. When importing it into matlab with ncread it is output as a int64:
0
609999895
1250000000
1859999895
2500000000
3119999885
3769999980
4380000114
5039999961
5650000095
6299999952
6910000085
I'm having trouble figuring out how to convert this to something understandable.
  2 Comments
KSSV
KSSV on 31 Oct 2022
You need to look into functions like datestr, datetime.
Emily Browning
Emily Browning on 31 Oct 2022
t = datetime(X,'ConvertFrom',dateType) This seam close but I can't find a dateType that fits.
In python the first value looks like 2022-08-23T22:03:51.200000047

Sign in to comment.

Answers (1)

Suvansh Arora
Suvansh Arora on 3 Nov 2022
One of the possible workarounds is to pre-process the date and time in python and convert it to Year, Month, Day, Hours, Minute and seconds.
Please follow below Python code snippet:
import numpy as np
import pandas as pd
# First datetime entry:
var = np.datetime64('2022-08-23T22:03:51.200000047')
# Helper function that converts above date-time to Hours, Months, Days, Seconds, years, etc:
def dt2cal(dt):
"""
Convert array of datetime64 to a calendar array of year, month, day, hour,
minute, seconds, microsecond with these quantites indexed on the last axis.
Parameters
----------
dt : datetime64 array (...)
numpy.ndarray of datetimes of arbitrary shape
Returns
-------
cal : uint32 array (..., 7)
calendar array with last axis representing year, month, day, hour,
minute, second, microsecond
"""
# allocate output
out = np.empty(dt.shape + (7,), dtype="u4")
# decompose calendar floors
Y, M, D, h, m, s = [dt.astype(f"M8[{x}]") for x in "YMDhms"]
out[..., 0] = Y + 1970 # Gregorian Year
out[..., 1] = (M - Y) + 1 # month
out[..., 2] = (D - M) + 1 # dat
out[..., 3] = (dt - D).astype("m8[h]") # hour
out[..., 4] = (dt - h).astype("m8[m]") # minute
out[..., 5] = (dt - m).astype("m8[s]") # second
out[..., 6] = (dt - s).astype("m8[us]") # microsecond
return out
Now we can Import this data to MATLAB and use datetime function to convert back to the required format, please follow below mentioned MATLAB code snippet for that:
% The arrays mentioned below, we will import from python
Y = [2014;2013;2012];
M = 01;
D = [31;30;31];
H = [1;2;3];
M = [12; 10; 1];
S = [1;1;1];
% Using datetime function to convert back, please refer documentation for details
t = datetime(Y,M,D,H,M,S)

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!