根据需求不同,一般工龄计算会有两种方案,一种是直接以天数表示,一种是以年月日的格式表示。两种情况的计算的方式不同,所以整理记录一下。
1、以天数的表示方式
思路:直接用两个日期相减,得到天数即可
1 from datetime import datetime 2 3 4 def cal_working_age(): 5 current_date = datetime.now().date() 6 begin_date = datetime.strptime("2010-01-01", "%Y-%m-%d").date() 7 8 return (current_date - begin_date).days 9 10 if __name__ == "__main__": 11 print(cal_working_age())
2、以年月日的格式来表示
思路:以年减年,月减月,日减日,不够则向前借。比如月不够减,则向年借12个月,所以这时年要再减一,以此类推。
1 from datetime import datetime 2 3 4 def cal_working_age_format(begin_date_str): 5 current_date = datetime.now().date() 6 begin_date = datetime.strptime(begin_date_str, "%Y-%m-%d").date() 7 begin_year = int(begin_date.year) 8 begin_month = int(begin_date.month) 9 begin_day = int(begin_date.day) 10 11 delta_year = current_date.year - begin_year 12 13 delta_month = current_date.month - begin_month 14 if delta_month < 0: 15 delta_year -= 1 16 delta_month = 12 + delta_month 17 18 delta_day = current_date.day - begin_day 19 if delta_day >= 0: 20 pass 21 else: 22 delta_month-=1 23 last_month_days = (datetime.datetime(year=current_date.year, month=current_date.month, day=1)-datetime.timedelta(days=1)).day 24 delta_day = last_month_days + delta_day 25 26 work_age = "{}年{}月{}日".format(delta_year, delta_month, delta_day) 27 28 return work_age 29 30 if __name__ == "__main__": 31 begin_date = "2010-01-01" 32 print(cal_working_age_format(begin_date))
3、同样是以年月日的格式来表示,还有另一种计算方法:
思路:先计算两个日期的月数差,用这个月数差除以12来算到年,余数为月,然后用当前时间-(开始时间+月数差)得到天数
1 import datetime 2 import calendar 3 4 # 获取两个日期的月数差 5 6 7 def get_months(begin_date, end_date): 8 return int(12 * (end_date.year - begin_date.year) + 9 (end_date.month - begin_date.month) + (end_date.day - begin_date.day) / 30) 10 11 # 给日期加月份 12 13 14 def add_months(source_date, months): 15 month = source_date.month - 1 + months 16 year = int(source_date.year + month / 12) 17 month = month % 12 + 1 18 day = min(source_date.day, calendar.monthrange(year, month)[1]) 19 return datetime.date(year, month, day) 20 21 22 if __name__ == "__main__": 23 today = datetime.datetime.now().date() 24 group_time = datetime.datetime.strptime("2013-10-14", "%Y-%m-%d").date() 25 26 delta_months = get_months(group_time, today) 27 year = int(delta_months / 12) 28 month = int(delta_months % 12) 29 days = (today - add_months(group_time, delta_months)).days 30 31 print("{}年{}月{}日".format(year, month, days))
TODO:以后遇到其他工龄计算的方式,再更新。