-1

I'm trying to calculate employee seniority in my report. The contract specifies the date of hiring and the end date. The difference gives the number of years in seniority. I have this formula which calculates it for me normally except that by generating the report for the month of February, I get errors probably because of the leap year. Here is the formula I use:

date_start = contract.date_start
date_end = contract.date_end
if not date_end :
    date_end = date.today()
timedelta = date_end - date_start
result = int(str(timedelta/365)[:2])

Wondering how to do that properly in python!

Any help would be appreciated!

  • 1
    Welcome to [so]. Please take into account that we have practically no idea about your specific setup. What type are ``date_start`` and ``date_end``? What kind of result is ``timedelta/365``? Why do you slice off two elements? Can you provide some sample input with expect and actual output? Take a moment to look through the [ask] and especially the [mre] help pages, then [edit] your question to help us help you. – MisterMiyagi Oct 28 '21 at 17:20
  • `timedelta` includes leap days. You don't need to parse the string, just use `timedelta.days`. – Barmar Oct 28 '21 at 17:22

2 Answers2

0

Assuming your contract's dates are datetime.date, you can check the number of full years between two dates using timedelta:

from dateutil.relativedelta import relativedelta
from datetime import date

date_start = contract.date_start
date_end = contract.date_end
if not date_end :
    date_end = date.today()
delta = relativedelta(date_end, date_start).years
Orijhins
  • 142
  • 5
  • This is the error I get when applying your code Error: forbidden opcode(s) in 'from dateutil.relativedelta import relativedelta\nfrom datetime import date\n\ndate_start = contract.date_start\ndate_end = contract.date_end\nif not date_end :\n date_end = date.today()\ndelta = relativedelta(date_end, date_start)\n': IMPORT_NAME, IMPORT_FROM – gerald BARY Oct 28 '21 at 18:13
  • We're lacking too much context to help you here... All I can tell you is that the error is about the import statements, not the actual code – Orijhins Oct 28 '21 at 18:28
0

I think you'll succeed using relativedelta

% pip3 install python-dateutil --user

Python code:

import datetime
import dateutil.relativedelta

t1 = datetime.datetime(2020, 1, 1)
t2 = datetime.datetime(2021, 1, 1)
t3 = datetime.datetime(2022, 1, 1)

print(f"Wrong: Using timedelta t2 - t1 = {(t2-t1)/365}")
print(f"Ok:    Using timedelta t3 - t2 = {(t3-t2)/365}")

print(f"Good:  Using relativedelta t2 - t1 = {dateutil.relativedelta.relativedelta(t2, t1)}")
print(f"Good:  Using relativedelta t3 - t2 = {dateutil.relativedelta.relativedelta(t3, t2)}")

Output:

Wrong: Using timedelta t2 - t1 = 1 day, 0:03:56.712329
Ok:    Using timedelta t3 - t2 = 1 day, 0:00:00
Good:  Using relativedelta t2 - t1 = relativedelta(years=+1)
Good:  Using relativedelta t3 - t2 = relativedelta(years=+1)
Sean Suchter
  • 328
  • 1
  • 6