Pandas: How to convert months since epoch to datetime?

Question:

If I have a dataframe with datetime:

df = pd.to_datetime([1, 32], unit='d',
           origin=pd.Timestamp('2022-01-01'))
df
>> DatetimeIndex(['2022-01-02', '2022-02-02'], dtype='datetime64[ns]', freq=None)

I can then retrieve the number of months since the epoch using:

df.to_period('M').astype(int)
>> Int64Index([624, 625], dtype='int64')

However, I would like to go the other way, e.g. to convert month number 624:

pd.to_datetime(624, format='%?')

Is this possible? What format will I need?

Asked By: Chris Snow

||

Answers:

I would suggest to add the DateOffset to the epoch Timestamp. Note: Here you will be loosing the day precision since there is no way for us to tell the exact day on the basis of only month number.

pd.Timestamp('1970-01-01') + pd.DateOffset(months=624)

Result

Timestamp('2022-01-01 00:00:00')
Answered By: Shubham Sharma
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.