Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python datetime to Matlab datenum

How do you convert a Python datetime to a Matlab datetnum?

like image 547
Jonathan Livni Avatar asked Jan 08 '12 08:01

Jonathan Livni


2 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.

like image 108
Roman Susi Avatar answered Sep 23 '22 11:09

Roman Susi


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
like image 29
Jonathan Livni Avatar answered Sep 22 '22 11:09

Jonathan Livni