Skip to content

Instantly share code, notes, and snippets.

@victorkristof
Last active March 31, 2023 14:59
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save victorkristof/b9d794fe1ed12e708b9d to your computer and use it in GitHub Desktop.
Save victorkristof/b9d794fe1ed12e708b9d to your computer and use it in GitHub Desktop.
Convert Matlab datenum into Python datetime
def datenum_to_datetime(datenum):
"""
Convert Matlab datenum into Python datetime.
:param datenum: Date in datenum format
:return: Datetime object corresponding to datenum.
"""
days = datenum % 1
hours = days % 1 * 24
minutes = hours % 1 * 60
seconds = minutes % 1 * 60
return datetime.fromordinal(int(datenum)) \
+ timedelta(days=int(days)) \
+ timedelta(hours=int(hours)) \
+ timedelta(minutes=int(minutes)) \
+ timedelta(seconds=round(seconds)) \
- timedelta(days=366)
@tkarna
Copy link

tkarna commented Aug 22, 2018

More succinct version following https://stackoverflow.com/a/13965852/8738113 :

def datenum_to_datetime(datenum):
    """
    Convert Matlab datenum into Python datetime.
    :param datenum: Date in datenum format
    :return:        Datetime object corresponding to datenum.
    """
    days = datenum % 1
    return datetime.fromordinal(int(datenum)) \
           + timedelta(days=days) \
           - timedelta(days=366)

@freerkschuett
Copy link

Very helpful, thanks

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