我最近开始用 Python 编码,我正在努力计算当前日期和给定日期之间的年数。
我想计算每一列的年数。我试过这个,但它不起作用:
def Number_of_years(d1,d2):
if d1 is not None:
return relativedelta(d2,d1).years
for col in df.select_dtypes(include=['datetime64[ns]']):
df[col]=Number_of_years(df[col],date.today())
任何人都可以帮我找到解决方案吗?
我看到日期的格式是日/月/年。
鉴于此格式对于所有网格都是相同的,您可以使用datetime
模块解析日期,如下所示:
from datetime import datetime # import module
def numberOfYears(element):
# parse the date string according to the fixed format
date = datetime.strptime(element, '%d/%m/%Y')
# return the difference in the years
return datetime.today().year - date.year
# make things more interesting by vectorizing this function
function = np.vectorize(numberOfYears)
# This returns a numpy array containing difference between years.
# call this for each column, and you should be good
difference = function(df.Date_creation)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句