According to the different needs, there are two schemes for the calculation of general length of service, one is directly expressed in days, and the other is expressed in the format of mm / DD / yyyy. The calculation methods of the two cases are different, so make a record.
1. In days
Idea: directly subtract two dates to get the number of days
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. In the form of MM DD YY
Idea: reduce year by year, month by month, and day by day. If not, borrow from others. If the month is not enough, then borrow 12 months from the year, so the year should be reduced one more time, and so on.
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+1, day=1)-datetime.timedelta(days=1)).day 24 delta_day = last_month_days + delta_day 25 26 work_age = "{}year{}month{}day".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))
TODO: in the future, when encountering other methods of seniority calculation, update them.