I am trying to convert a pandas dataframe column of matlab datenum format to python date time format using the function below:
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
date = datetime.fromordinal(int(datenum)) \
+ timedelta(days=days) \
- timedelta(days=366)
return date.year
A sample of the values
0 693726
1 693726
2 693726
3 693726
4 693726
...
460718 726831
460719 726831
460720 726831
460721 726831
460722 726831
Name: dob, Length: 460723, dtype: int32
But I get the error below when I try to apply the function.
df['dob'] = df['dob'].apply(datenum_to_datetime)
OverflowError Traceback (most recent call last)
<ipython-input-67-cc4fb607b497> in <module>()
----> 1 df['dob'] = df['dob'].apply(datenum_to_datetime)
2 df.head()
1 frames
pandas/_libs/lib.pyx in pandas._libs.lib.map_infer()
<ipython-input-66-bab915eae5ff> in datenum_to_datetime(datenum)
6 """
7 days = datenum % 1
----> 8 date = datetime.fromordinal(int(datenum)) + timedelta(days=2) - timedelta(days=366)
9
10 return date.year
OverflowError: date value out of range