How do you convert a Python datetime to a Matlab datetnum?
3 Answers
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.
Comments
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
Comments
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
2 Comments
Amro
+1 slightly off-topic, but I had to do a similar conversion between MATLAB
datenum and C# System.DateTime in an old answer of mine. Beside the different units used internally, the reference point in time was also off by 366 days: stackoverflow.com/a/7558811/97160Jonathan Livni
actually
datestr(734912.28891203704, 'mmmm dd, yyyy HH:MM:SS.FFF AM') yields February 13, 2012 6:56:02.000 AM so it does not retain the milliseconds\microseconds information
datenum's textual representation which Matlab knows how to read. stuff like732399.65465where on the left is the gregorian day since 1/1/1 (or 1/1/0?!) and on the right is the fraction of a day