主要内容

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

MATLAB Compiler SDK 和 Python 之间传递持续时间数据

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

此示例演示了如何创建一个使用 MATLAB® Compiler SDK™ 在 Python® 和 MATLAB 之间传递持续时间数据的 Python 应用程序。Python 脚本调用了两个打包的 MATLAB 函数,这些函数以持续时间数据作为输入或输出。

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

前提条件

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

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

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

创建 MATLAB 函数,接受 duration 作为输入参数。

此 MATLAB 函数以 duration 作为输入。它计算数组 duration 中最长的 duration。将此函数保存为 getLongestDuration.m

function longestDuration = getLongestDuration(durArray)
%   Given an array of durations, return the longest duration
    longestDuration = max(durArray);
end

创建名为 MATLAB 的函数,其输出为 duration

此 MATLAB 函数返回一个 duration。此函数用于计算两个日期时间之间的时长。将此函数保存为 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

从函数创建 Python

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

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

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

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

编写 Python 应用程序代码

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

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

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

  • 导入 durationLibmatlabdatetimenumpy 包。

  • durationLib 实例实例化为 my_durationLib

  • 创建一个名为 duration_list 的持续时间列表。

  • 将列表转换为名为 timedelta_arrtimedelta64 NumPy 数组。

  • 调用封装函数 longestDurationdurAtoB

  • 显示结果。

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

安装并运行 Python

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

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

python -m pip install .

运行该应用程序。

python testDurationFunctions.py

该应用程序生成此输出。

The longest timedelta in the list is: 22:17:45
The timedelta between the two datetimes is: -1 day, 21:00:00

另请参阅

主题