5

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

2
  • 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? Commented Jan 8, 2012 at 9: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 Commented Jan 8, 2012 at 14:14

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

9

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

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

2 Comments

+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/97160
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.