问题
How do you convert a Python datetime to a Matlab datetnum?
回答1:
To serialize datetime as a string, strftime can be used on the Python side:
import datetime
d = datetime.datetime.now()
print (d.strftime("%d-%b-%Y %H:%M:%S"))
According to MatLab docs datenum knows how to parse it.
回答2:
Based on bavaza's answer - now including microseconds:
def datetime2matlabdn(dt):
mdn = dt + timedelta(days = 366)
frac_seconds = (dt-datetime.datetime(dt.year,dt.month,dt.day,0,0,0)).seconds / (24.0 * 60.0 * 60.0)
frac_microseconds = dt.microsecond / (24.0 * 60.0 * 60.0 * 1000000.0)
return mdn.toordinal() + frac_seconds + frac_microseconds
回答3:
Reversing what was done here, I got:
def datetime2matlabdn(dt):
ord = dt.toordinal()
mdn = dt + timedelta(days = 366)
frac = (dt-datetime(dt.year,dt.month,dt.day,0,0,0)).seconds / (24.0 * 60.0 * 60.0)
return mdn.toordinal() + frac
Should work with timedelta.microseconds too.
In IDLE:
n = datetime.now()
datetime.datetime(2012, 2, 13, 6, 56, 2, 619000)
datetime2matlabdn(n)
734912.28891203704
In Matlab:
>> datestr(734912.28891203704)
ans =
13-Feb-2012 06:56:02
来源:https://stackoverflow.com/questions/8776414/python-datetime-to-matlab-datenum