问题
D = ["10Aug49","21Jan45","15Sep47","13Jun52"], convert this into pandas date, make sure that year is 1900 not 2000. So far i have this code which converts and prints the pandas date but century is 2000, i want 1900.
import pandas as pd
from datetime import datetime
Dae = pd.Series(["10Aug49","21Jan45","15Sep47","13Jun52"])
x =[]
for i in Dae:
x = datetime.strptime(i,"%d%b%y")
print(x)
回答1:
I feel better to correct the year first, then convert to datetime:
# identify the year as the last group of digits and prepend 19
corrected_dates = Dae.str.replace('(\d+)$',r'19\1')
# convert to datetime
pd.to_datetime(corrected_dates)
Output:
0 1949-08-10
1 1945-01-21
2 1947-09-15
3 1952-06-13
dtype: datetime64[ns]
回答2:
from datetime import date
import pandas as pd
from datetime import datetime
Dae = pd.Series(["10Aug49","21Jan45","15Sep47","13Jun52"])
x =[]
new_list = []
for i in Dae:
i = datetime.strptime(i,"%d%b%y").date()
if date.today() <= i:
i = i.replace(year=i.year - 100)
new_list.append(i)
print(new_list)
[datetime.date(1949, 8, 10), datetime.date(1945, 1, 21), datetime.date(1947, 9, 15), datetime.date(1952, 6, 13)]
来源:https://stackoverflow.com/questions/61125714/converting-series-to-pandas-datetime