필터 지우기
필터 지우기

Python datetime4[ns] to MATLAB

조회 수: 11 (최근 30일)
Emily Browning
Emily Browning 2022년 10월 31일
답변: Suvansh Arora 2022년 11월 3일
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
KSSV
KSSV 2022년 10월 31일
You need to look into functions like datestr, datetime.
Emily Browning
Emily Browning 2022년 10월 31일
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

댓글을 달려면 로그인하십시오.

답변 (1개)

Suvansh Arora
Suvansh Arora 2022년 11월 3일
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)

카테고리

Help CenterFile Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by