1
votes

I'm working with times in Matlab using datenum including milliseconds (datenum('2019-10-16 23:58:57.970') == 737714.999282060) and I want to get the same number in python but I get a different number (about 3 hours of error)

I know that datenum return days since year 1 and timestamp() returns seconds since 1970, so:

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

Other example gives 2.9998057410120964 of error (very similar but not equal, so I can't use the error as a constant to fix the problem)

1

1 Answers

2
votes

you need to set a time zone (here: UTC); otherwise, timestamp() assumes the datetime object you call the method on is local time and adds/subtracts the corresponding UTC offset in seconds.

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

Side note: you might want to have a look at Matlab's datetime format conversion functions as well, e.g. if you have

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

in Matlab, you get the exact same value in Python:

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