You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何测试变量是否为numpy.datetime64类型?我的验证代码为何失效?

验证numpy.datetime64类型的正确方式

你代码里的核心问题是isinstance的第二个参数传错了——numpy.datetime64()是创建了一个datetime64实例,而非类型对象。isinstance要求第二个参数必须是类型或类型元组,这直接导致断言失败。

两种正确的验证方式:

  1. 直接传入类型对象
    把断言里的numpy.datetime64()改成numpy.datetime64即可:

    import numpy
    
    def test_write_limit_orders(mock_write_limit_order, exchange):
        exchange.context.capture_tstamp = numpy.datetime64("2022-06-16T22:10:00.314635081")
    
        # 正确写法:传入类型而非实例
        assert isinstance(exchange.context.capture_tstamp, numpy.datetime64)
    
  2. 检查dtype(适配带单位的场景)
    部分场景下numpy的datetime64会附带时间单位(比如datetime64[ns]),直接用isinstance不够精准,这时可以通过dtype判断:

    import numpy
    
    def test_write_limit_orders(mock_write_limit_order, exchange):
        exchange.context.capture_tstamp = numpy.datetime64("2022-06-16T22:10:00.314635081")
    
        # 检查dtype是否属于datetime64类型
        assert numpy.issubdtype(exchange.context.capture_tstamp.dtype, numpy.dtype('datetime64'))
    

内容的提问来源于stack exchange,提问作者Patrick_Chong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 21:27:35