2

I have to convert a MATLAB's datenum to Python's datetime. The following code is as below:

import datetime
matlab_datenum = 63650571169.50261
python_datetime = datetime.date.fromordinal(int(matlab_datenum)) + \
    datetime.timedelta(days=matlab_datenum%1) - datetime.timedelta(days=366)
print(matlab_datenum)

The above code generates this error:

OverflowError: Python int too large to convert to C long

How, can I resolve this problem?

2
  • 63650571169.50261 this number seems to big to be a MATLAB datenum first of all, MATLAB datenums are number of days from January 0, 0000, this number is equivalent to 174385126 years. Is this the time when aliens are going to make contact ? The overflow issue could be related to this Commented Mar 31, 2017 at 2:18
  • 63650571169.50261 is a datenum that represents a date plus a time for example 2010-11-04 00:03:50.209589. so, how can i obtain a date plus a time ? Commented Mar 31, 2017 at 9:40

1 Answer 1

1

Your datenum is in seconds from the matlab epoch. To convert to a datetime you need to offset that number of seconds to a datetime that python understands. This function uses the Unix epoch as that reference.

Code:

import datetime as dt

# define some constants
epoch = dt.datetime(1970, 1, 1)
matlab_to_epoch_days = 719529  # days from 1-1-0000 to 1-1-1970
matlab_to_epoch_seconds = matlab_to_epoch_days * 24 * 60 * 60

def matlab_to_datetime(matlab_date_num_seconds):
    # get number of seconds from epoch
    from_epoch = matlab_date_num_seconds - matlab_to_epoch_seconds

    # convert to python datetime
    return epoch + dt.timedelta(seconds=from_epoch)

Test Code:

print(matlab_to_datetime(63650571169.50261))

Results:

2017-01-01 10:12:49.502609
Sign up to request clarification or add additional context in comments.

Comments

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.