Skip to content

Instantly share code, notes, and snippets.

@zertrin
Created January 29, 2013 10:02
Show Gist options
  • Save zertrin/4663169 to your computer and use it in GitHub Desktop.
Save zertrin/4663169 to your computer and use it in GitHub Desktop.
Function to convert a Python datetime to a Matlab datenum. From http://stackoverflow.com/questions/8776414/python-datetime-to-matlab-datenum/9260102#9260102
from datetime import datetime, timedelta
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
@litao-wrk
Copy link

can't subtract offset-naive and offset-aware datetimes...

@walidbou6
Copy link

just add the following line dt = dt.replace(tzinfo=None)

def datetime2matlabdn(dt):
    dt = dt.replace(tzinfo=None)
    ord = dt.toordinal()
    mdn = dt + timedelta(days = 366)
    frac = (dt-datetime(dt.year,dt.month,dt.day,dt.second)).seconds / (24.0 * 60.0 * 60.0)
    return mdn.toordinal() + frac

this function doesn't really give the same results as Matlab
ex:

s = '2016-01-17T23:00:00.1173350Z'
matlab_datenum = 73635.0
python_datenum = 736346.9583333334

there's a difference by 4 values

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment