Equivalent function of datenum(datestring) of Matlab in Python

I would use the datetime module and the toordinal() function

from datetime import date

print date.toordinal(date(1970,1,1))

719163

To get the date you got you would use

print date.toordinal(date(1971,1,2))

719529

or for easier conversion

print date.toordinal(date(1970,1,1))+366

719529

I believe the reason the date is off is due to the fact datenum starts its counting from january 0, 0000 which this doesn't recognize as a valid date. You will have to counteract the change in the starting date by adding one to the year and day. The month doesn't matter because the first month in datetime is equal to 0 in datenum


The previous answers return an integer. MATLAB's datenum does not necessarily return an integer. The following code retuns the same answer as MATLAB's datenum:

from datetime import datetime as dt

def datenum(d):
    return 366 + d.toordinal() + (d - dt.fromordinal(d.toordinal())).total_seconds()/(24*60*60)

d = dt.strptime('2019-2-1 12:24','%Y-%m-%d %H:%M')
dn = datenum(d)

You can substract date objects in Python:

>>> date(2015, 10, 7) - date(1, 1, 1)
datetime.timedelta(735877)

>>> (date(2015, 10, 7) - date(1, 1, 1)).days
735877

Just take care to use an epoch that is useful to your needs.

Tags:

Python

Matlab