【问题标题】:Matlab datenum to python, I get error of about 3 hoursMatlab datenum 到 python,我得到大约 3 小时的错误
【发布时间】:2020-11-13 00:48:54
【问题描述】:

我在 Matlab 中使用 datenum 处理时间,包括毫秒 (datenum('2019-10-16 23:58:57.970') == 737714.999282060),我想在 python 中获得相同的数字,但我得到了不同的数字数字(大约 3 小时的错误)

我知道 datenum 返回自第 1 年以来的天数,而 timestamp() 返回自 1970 年以来的秒数,所以:

datenum1970 = 719529 #datenum('1970-01-01 00:00:00.0')

datenum_example_2 = 737714.999282060 #datenum('2019-10-16 23:58:57.970'), some date
d_example_2 = datetime(2019,10,16,23,58,57,970) #same date in datetime library
d_example_2_days = d_example_2.timestamp()/(24*3600) + datenum1970 # == 737715.1242708445

(d_example_2_days - datenum_example_2)*24 ==  2.9997308291494846 # thats the error, about 3 hours

其他示例给出 2.9998057410120964 的错误(非常相似但不相等,所以我不能将错误用作常量来解决问题)

【问题讨论】:

    标签: python matlab datetime timestamp


    【解决方案1】:

    您需要设置时区(此处为:UTC);否则,timestamp() 假定您调用该方法的日期时间对象是本地时间,并以秒为单位添加/减去相应的 UTC 偏移量。

    from datetime import datetime, timezone
    
    datenum1970 = 719529 #datenum('1970-01-01 00:00:00.0')
    datenum_example_2 = 737714.999282060 #datenum('2019-10-16 23:58:57.970'), some date
    d_example_2 = datetime(2019,10,16,23,58,57,970, tzinfo=timezone.utc)
    
    d_example_2_days = d_example_2.timestamp()/(24*3600) + datenum1970
    # 737714.9992708445
    
    (d_example_2_days - datenum_example_2)*24
    # -0.0002691708505153656
    

    旁注:您可能还想看看 Matlab 的日期时间格式转换函数,例如如果你有

    ts_m = posixtime(datetime('2019-10-16 23:58:57'))
    % 1.571270337000000e+09
    % (use datetime(X, 'ConvertFrom', 'datenum') to get datetime from datenum)
    

    在 Matlab 中,您在 Python 中得到完全相同的值:

    ts_p = datetime.fromisoformat('2019-10-16 23:58:57').replace(tzinfo=timezone.utc).timestamp()
    # 1571270337.0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-26
      • 1970-01-01
      • 2017-06-18
      相关资源
      最近更新 更多