主要内容

本页采用了机器翻译。点击此处可查看最新英文版本。

MATLAB Compiler SDK 和 Python 之间传递日期时间数据

支持的平台:Windows®、Linux®Mac

此示例演示了如何创建一个使用 MATLAB® Compiler SDK™ 在 Python® 和 MATLAB 之间传递日期时间数据的 Python 应用程序。Python 脚本调用了两个打包的 MATLAB 函数,这些函数用于处理来自气象站的日期时间数据。当您将 MATLAB datetime 标量传递给 Python 时,MATLAB Compiler SDK 会将其转换为 datetime.datetime 对象。

当您将一个 MATLAB datetime 数组传递给 Python 时,如果 Python 环境中没有 NumPy,则 MATLAB Compiler SDK 将数据转换为一个 matlab.object 数组;如果 Python 环境中有 NumPy,则转换为一个 numpy.datetime64 数组。当您将一个 Python datetime.datetimenumpy.datetime64 传递给 MATLAB 时,MATLAB Compiler SDK 会将数据转换为 datetime。有关数据类型及其转换的完整列表,请参阅在 MATLAB 和 Python 之间传递数据

前提条件

验证您所安装的 Python 版本是否与 MATLAB Compiler SDK 兼容。有关详细信息,请参阅MATLABCompiler SDK Python 目标要求

目标计算机需要 MATLAB Runtime 来运行已部署的 MATLAB 代码。您可以将 MATLAB Runtime 包含在 Python 包的安装程序中,也可以单独安装它。有关详细信息,请参阅下载并安装 MATLAB Runtime

NumPy 包对于 MATLAB Compiler SDK 通常不是必需的,但该包允许您将 MATLAB 运行时 datetime 数组转换为 Python numpy.datetime64 数组。

创建 MATLAB 函数,返回 datetime 标量输出

创建一个 MATLAB 函数,该函数接受 datetime 作为输入,计算 datetime 数组中的最新 datetime,并返回一个 datetime 标量。将此函数保存为 getLatestDateTime.m

function latestDateTime = getLatestDateTime(dtArray)
% Given an array of datetimes, return the most recent datetime.
    latestDateTime = max(dtArray);
end

创建带有 datetime 数组输出的 MATLAB 函数

创建一个返回 datetime 数组的 MATLAB 函数。该函数接受一个整数标量、一个 datetime 数组和一个整数数组,并返回一个数组,该数组包含与 k 最高温度相对应的日期时间以及最高整体温度出现的日期时间。将此函数保存为 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

从函数创建 Python

使用 Python 包编译器compiler.build.pythonPackage 函数构建 Python 包。

例如,如果您正在使用 compiler.build.pythonPackage,首先获取当前目录下所有以 .m 为扩展名的文件列表。

functionfiles = dir('*.m');
然后,将文件名保存在元胞数组中。
functionfiles = {functionfiles.name};
接下来,编译 Python 包。
buildResults = compiler.build.pythonPackage(functionfiles,'PackageName','datetimeLib');

有关详细信息,请参阅生成 Python 包并编译 Python 应用程序

编写 Python 应用程序代码

使用 Python 编写代码,用于名为 testDatetimeFunctions.py 的应用程序。此示例应用程序包含用于测试打包的 MATLAB 函数的驱动代码。

#!/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()

该应用程序执行以下步骤:

  • 导入 datetimeLibmatlabdatetimenumpy 包。

  • datetimeLib 实例实例化为 my_datetimeLib

  • 创建一个名为 datetime_list 的日期时间列表。

  • 将列表转换为名为 datetime_arrdatetime64 NumPy 数组,该数组可作为打包函数的输入。

  • 调用封装函数 getKHottestTimesgetLatestDateTime

  • 显示结果。

  • 使用 try 模块来捕获和处理异常。

安装并运行 Python

在目标计算机上,安装生成的 Python 包。有关详细信息,请参阅安装并导入 MATLAB Compiler SDK Python 包

在系统命令提示符中,导航到包含生成文件的文件夹并安装 Python 包。

python -m pip install .

运行该应用程序。

python testDatetimeFunctions.py

该应用程序生成以下输出。

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

另请参阅

主题