Jayant
Jayant

Reputation: 83

Python convert date format to datetime accurately which includes dates before 1970

Consider python panda code as

datetest = pd.DataFrame({'year':['02','08',23,32,43,68,70,72,85,94]})
newdate = pd.to_datetime(datetest['year'], format='%y')
print(newdate)

Output:

0   2002-01-01
1   2008-01-01
2   2023-01-01
3   2032-01-01
4   2043-01-01
5   2068-01-01
6   1970-01-01
7   1972-01-01
8   1985-01-01
9   1994-01-01
Name: year, dtype: datetime64[ns]

So how can I convert 2023, 2032, 2043, 2068 to 1923, 1932, 1943, 1968 respectively keeping datetime format intact?

Upvotes: 1

Views: 224

Answers (1)

Chris Adams
Chris Adams

Reputation: 18647

You could do use boolean indexing and pandas.DateOffset to adjust any dates in the future by 100 years.

If this rule is too strict, you can set your own threshold for what an acceptible year might be:

year = pd.datetime.today().year

# If setting your own threshold year eg.
# year = 2030

newdate.loc[newdate.dt.year.gt(year)] -= pd.DateOffset(years=100)

[out]

0   2002-01-01
1   2008-01-01
2   1923-01-01
3   1932-01-01
4   1943-01-01
5   1968-01-01
6   1970-01-01
7   1972-01-01
8   1985-01-01
9   1994-01-01
Name: year, dtype: datetime64[ns]

Upvotes: 3

Related Questions