5

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

Jonathan Livni
  • 101,334
  • 104
  • 266
  • 359
  • 1
    Do you actually mean convert an object in one language to an object in another? If so, what interface are you using (PyMat?) Or do you mean how do you print out a datetime object in a particular format? – David Robinson Jan 08 '12 at 09:20
  • @DavidRobinson - nope, I mean to `datenum`'s textual representation which Matlab knows how to read. stuff like `732399.65465` where 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 – Jonathan Livni Jan 08 '12 at 14:14

3 Answers3

9

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.

Roman Susi
  • 4,135
  • 2
  • 32
  • 47
8

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
Jonathan Livni
  • 101,334
  • 104
  • 266
  • 359
6

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

Community
  • 1
  • 1
bavaza
  • 10,319
  • 10
  • 64
  • 103
  • +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: http://stackoverflow.com/a/7558811/97160 – Amro Feb 13 '12 at 18:03
  • 1
    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 – Jonathan Livni Feb 22 '12 at 08:50