Skip to content

Instantly share code, notes, and snippets.

@joefutrelle
Created April 26, 2022 16:15
Show Gist options
  • Save joefutrelle/be4317399550f0998d21c2aac6a03716 to your computer and use it in GitHub Desktop.
Save joefutrelle/be4317399550f0998d21c2aac6a03716 to your computer and use it in GitHub Desktop.
Convert MATLAB datenums to/from Python datetimes
from datetime import datetime, timedelta
# util for converting MATLAB datenum to Python datetime
# as described in http://stackoverflow.com/questions/13965740/converting-matlabs-datenum-format-to-python
def datenum2datetime(matlab_datenum):
dt = datetime.fromordinal(int(matlab_datenum)) + timedelta(days=matlab_datenum%1) - timedelta(days = 366)
return dt
# util for converting datetime to MATLAB datenum
# as described in http://stackoverflow.com/questions/8776414/python-datetime-to-matlab-datenum
def datetime2datenum(dt):
dt = dt.replace(tzinfo=None)
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment