Pass Datetime 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 datetime data between Python and MATLAB. The Python script calls two packaged MATLAB functions that work with datetime data from a weather station. When you
pass a MATLAB
datetime
scalar to Python, MATLAB
Compiler SDK converts it into a datetime.datetime
object.
When you pass a MATLAB
datetime
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.datetime64
array if NumPy
is available in the Python environment. When you pass a Python
datetime.datetime
or numpy.datetime64
to
MATLAB, MATLAB
Compiler SDK converts the data into a datetime
. 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 the package allows you to convert MATLAB Runtime
datetime
arrays to Python numpy.datetime64
arrays.
Create MATLAB Function with datetime
Scalar Output
Create a MATLAB function that takes a datetime
as input, calculates
the latest datetime
in a datetime
array and
returns a datetime
scalar. Save this function as
getLatestDateTime.m
.
function latestDateTime = getLatestDateTime(dtArray) % Given an array of datetimes, return the most recent datetime. latestDateTime = max(dtArray); end
Create MATLAB Function with datetime
Array Output
Create a MATLAB function that returns a datetime
array. The
function takes an integer scalar, a datetime
array and an integer
array, and returns an array of datetimes corresponding to the k
hottest temperatures and the datetime at which the hottest overall temperature
occurs. Save this function as
getKHottestTimes.m
.
function kMaxTempTimes = getKHottestTimes(k, dtArray, tempArray) % Given an integer 0<k<length(dtArray), an array of datetimes and a % corresponding array of temperatures in degrees F at those datetimes, % return the k hottest times. If given a value outside this range for % k, set k equal to the length of the array. if k < 1 || k > length(dtArray) k = length(dtArray); end % Get the k max temperatures. % Then, get the corresponding times. [~, kMaxTempIdx] = maxk(tempArray, k); kMaxTempTimes = dtArray(kMaxTempIdx); 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','datetimeLib');
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 testDatetimeFunctions.py
.
This sample application contains driver code to test the packaged MATLAB
functions.
#!/usr/bin/env python
import datetimeLib
# 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_datetimeLib = datetimeLib.initialize()
except Exception as e:
print("Error initializing datetimeLib package\\n:{}".format(e))
exit(1)
try:
# Create array of datetime data for the past 24 hours
datetime_list = [
dt.datetime.strptime(i, "%Y-%m-%d %H:%M")
for i in [
"2024-10-30 18:00",
"2024-10-30 21:00",
"2024-10-31 00:00",
"2024-10-31 03:00",
"2024-10-31 06:00",
"2024-10-31 09:00",
"2024-10-31 12:00",
"2024-10-31 15:00",
"2024-10-31 18:00"
]
]
datetime_arr = np.array([np.datetime64(dt) for dt in datetime_list])
temps = np.array([67, 64, 62, 60, 58, 61, 70, 75, 79])
# Call the packaged functions.
yOut = my_datetimeLib.getKHottestTimes(5, datetime_arr, temps)
print("The hottest times of day are: " + str(yOut))
yOut = my_datetimeLib.getLatestDateTime(datetime_arr)
print("The latest datetime is: " + str(yOut))
except Exception as e:
print("Error occurred during program execution\\n:{}".format(e))
my_datetimeLib.terminate()
The application performs these steps:
Imports the
datetimeLib
,matlab
,datetime
andnumpy
packages.Instantiates the
datetimeLib
instance asmy_datetimeLib
.Creates a list of datetimes called
datetime_list
.Converts the list to a
datetime64
NumPy array calleddatetime_arr
, which can be used as input for the packaged function.Calls the packaged functions
getKHottestTimes
andgetLatestDateTime
.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 testDatetimeFunctions.py
The application generates the following output.
The hottest times of day are: ['2024-10-31T18:00:00.000000000' '2024-10-31T15:00:00.000000000' '2024-10-31T12:00:00.000000000' '2024-10-30T18:00:00.000000000' '2024-10-30T21:00:00.000000000'] The latest datetime is: 2024-10-31 18:00:00
See Also
Topics
- Pass Duration Data Between MATLAB Compiler SDK and Python
- Convert Between MATLAB tables and Pandas DataFrames
- Calculate Win Percentage Using Python Dictionary Data
- matlab Python Module (MATLAB Production Server)
- Use MATLAB Arrays in Python (MATLAB Production Server)
- Invoke Packaged MATLAB Functions (MATLAB Production Server)