Pass Duration Data Between MATLAB Compiler SDK and Python
Supported platforms: Windows®, Linux®, Mac
This example shows how to create a Python® application that uses MATLAB® Compiler SDK™ to pass duration data between Python and MATLAB. The Python script calls two packaged MATLAB functions that use duration data as input or output.
When you pass a MATLAB
duration
scalar to Python, MATLAB
Compiler SDK converts the data into a datetime.timedelta
object.
When you pass a MATLAB
duration
array to Python, MATLAB
Compiler SDK converts the data into a matlab.object
array if NumPy
is not available in the Python environment, or into a numpy.timedelta64
array if NumPy
is available in the Python environment. When you pass a Python
datetime.timedelta
or numpy.timedelta64
to
MATLAB, MATLAB
Compiler SDK converts the data into a duration
. For a complete list
of data types and their conversions, see Pass Data Between MATLAB and Python.
Prerequisites
Verify that you have a version of Python installed that is compatible with MATLAB Compiler SDK. For details, see MATLAB Compiler SDK Python Target Requirements.
The target machine requires MATLAB Runtime to run the deployed MATLAB code. You can include MATLAB Runtime in an installer for your Python package or install it separately. For details, see Download and Install MATLAB Runtime.
The NumPy package is not required for MATLAB
Compiler SDK in general, but allows you to convert MATLAB Runtime
duration
arrays to Python numpy.timedelta64
arrays.
Create MATLAB Function with duration
Input
This MATLAB function takes a duration
as input. It calculates
the longest duration
in a duration
array. Save
this function as
getLongestDuration.m
.
function longestDuration = getLongestDuration(durArray) % Given an array of durations, return the longest duration longestDuration = max(durArray); end
Create MATLAB Function with duration
Output
This MATLAB function returns a duration
. This function finds
the duration between two datetimes. Save this function as
durAtoB.m
.
function durBetween = durAtoB(dtA, dtB) % Given two datetimes, find the duration % between them. % Since between() returns a calendarDuration, % convert it to a duration calDurBetween = between(dtA, dtB); durBetween = time(calDurBetween); end
Create Python Package from Function
Build the Python package with the Python Package Compiler app or the
compiler.build.pythonPackage
function.
For example, if you are using compiler.build.pythonPackage
,
start by getting a list of files with a .m
extension in the
current
directory.
functionfiles = dir('*.m');
functionfiles = {functionfiles.name};
buildResults = compiler.build.pythonPackage(functionfiles,'PackageName','durationLib');
For details, see the instructions in Generate Python Package and Build Python Application.
Write Python Application Code
Write code in Python for an application named testDurationFunctions.py
.
This sample application contains driver code to test the packaged MATLAB
functions.
#!/usr/bin/env python
import durationLib
# Import the matlab module only after you have imported
# MATLAB Compiler SDK generated Python modules.
import matlab
import datetime as dt
import numpy as np
try:
# Initialize the Python module created with MATLAB Compiler SDK.
my_durationLib = durationLib.initialize()
except Exception as e:
print("Error initializing durationLib package\\n:{}".format(e))
exit(1)
try:
# Create the duration array.
string_list = [
dt.datetime.strptime(i, "%H:%M:%S")
for i in [
"02:23:41",
"17:46:39",
"03:47:10",
"06:12:08",
"12:29:30",
"03:27:57",
"02:39:21",
"21:42:35",
"15:45:14",
"22:17:45"
]
]
timedelta_arr = np.array([np.timedelta64(t.hour, 'h')+
np.timedelta64(t.minute, 'm')+
np.timedelta64(t.second, 's')
for t in string_list])
# Call the packaged functions.
yOut = my_durationLib.getLongestDuration(timedelta_arr)
print("The longest timedelta in the list is: " + str(yOut))
yOut = my_durationLib.durAtoB(dt.datetime(2024, 10, 31, 18, 0),
dt.datetime(2024, 10, 31, 15, 0))
print("The timedelta between the two datetimes is: " + str(yOut))
except Exception as e:
print("Error occurred during program execution\\n:{}".format(e))
my_durationLib.terminate()
The application performs these steps:
Imports the
durationLib
,matlab
,datetime
andnumpy
packages.Instantiates the
durationLib
instance asmy_durationLib
.Creates a list of durations called
duration_list
.Converts the list to a
timedelta64
NumPy array calledtimedelta_arr
.Calls the packaged functions
longestDuration
anddurAtoB
.Displays the result.
Uses a
try
block to catch and handle exceptions.
Install and Run Python Package
On the target machine, install the generated Python package. For more details, see Install and Import MATLAB Compiler SDK Python Packages.
In the system command prompt, navigate to the folder containing the generated files and install the Python package.
python -m pip install .
Run the application.
python testDurationFunctions.py
The application generates this output.
The longest timedelta in the list is: 22:17:45 The timedelta between the two datetimes is: -1 day, 21:00:00
See Also
Topics
- Pass Datetime Data Between MATLAB Compiler SDK and Python
- Convert Between MATLAB tables and Pandas DataFrames
- Use MATLAB Arrays in Python (MATLAB Production Server)
- Calculate Win Percentage Using Python Dictionary Data
- matlab Python Module (MATLAB Production Server)
- Invoke Packaged MATLAB Functions (MATLAB Production Server)