Working with Pandas DataFrame: I want to add missing year in timestamp column which includes month/day and time

Question:

I have timestamps but the year is missing. Currently the column is object/series and I want to convert it to datetime format using ‘pd.to_datetime’ but since the year is missing I am getting an error message. How can I insert the year "2020" to the timestamps shown below:

DateTime
1    01/01  00:02:00
2    01/01  00:04:00
...
262799   12/31  23:58:00
262800   12/31  24:00:00

I would like to have this output but I do not know how to get it:

DateTime
1    2020/01/01  00:02:00
2    2020/01/01  00:04:00
....
262800   2020/12/31  24:00:00
Asked By: user369273

||

Answers:

Use string concatenation:

df['DateTime'] = '2020/' + df['DateTime']

Or to datetime:

df['DateTime'] = pd.to_datetime('2020/' + df['DateTime'], dayfirst=False)
Answered By: mozway
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.