How to Calculate Employee Tenure in Excel Using Python and Openpyxl

How to Calculate Employee Tenure in Excel Using Python and Openpyxl
Image by Editor | Midjourney

When managing employee data in Excel, tracking how long each person has been with the company often involves complex date calculations. While Excel formulas can handle these calculations, using Python with openpyxl lets you automate the process and handle multiple files consistently. In this article, we’ll show how to build a comprehensive employee tenure tracking system step by step.

Setting Up the Employee Data Structure

First, let’s create an Excel workbook containing employee records with their start dates, current dates, and departments. We’ll use openpyxl to set up this foundation, ensuring our dates are properly formatted and our columns are clearly labeled.

 
# Block 1: Basic Setup and Data Entry
from openpyxl import Workbook
from openpyxl.styles import Font
from datetime import datetime, date

# Create a new workbook and select active sheet
wb = Workbook()
ws = wb.active
ws.title = "Employee Tenure"

# Add headers with formatting
headers = ["Employee Name", "Start Date", "Current Date", "Department"]
for col, header in enumerate(headers, 1):
    cell = ws.cell(row=1, column=col, value=header)
    cell.font = Font(bold=True)

# Sample employee data
employees = [
    ("John Smith", "2010-03-15", "2025-02-24", "Sales"),
    ("Mary Johnson", "2018-06-01", "2025-02-24", "Engineering"),
    ("Robert Brown", "2015-09-20", "2025-02-24", "Marketing"),
    ("Sarah Davis", "2022-01-10", "2025-02-24", "Sales"),
    ("Michael Wilson", "2019-11-05", "2025-02-24", "Engineering"),
    ("Emma Taylor", "2012-07-30", "2025-02-24", "Marketing")
]

# Add employee data
for row, (name, start, current, dept) in enumerate(employees, 2):
    ws.cell(row=row, column=1, value=name)
    ws.cell(row=row, column=2, value=start)
    ws.cell(row=row, column=3, value=current)
    ws.cell(row=row, column=4, value=dept)

# Adjust column widths
for col in ws.columns:
    max_length = max(len(str(cell.value)) for cell in col)
    ws.column_dimensions[col[0].column_letter].width = max_length + 2

wb.save('employee_tenure_step1.xlsx')

This code creates:

  • A new Excel workbook titled “Employee Tenure”
  • Four columns for employee information
  • Sample data for six employees across different departments
  • Auto-adjusted column widths for better readability

When you run this code, you’ll get an Excel file that looks like this:


A table displaying employee names, start dates, a current date, and department names.
Image By Author
 

Each column is sized appropriately to its content, and the headers are formatted in bold for clear visibility. This gives us a solid foundation for adding tenure calculations in the next section. 

Calculating Employee Tenure

Next, we’ll add functionality to calculate how long each employee has been with the company. Instead of using complex Excel formulas, we’ll create a Python function that computes years and months of service from the start date to the current date. This calculation handles edge cases like different month lengths and accounts for partial months correctly.

 
# Block 2: Adding Tenure Calculations
from openpyxl import load_workbook
from openpyxl.styles import Font
from datetime import datetime

def calculate_tenure_components(start_date_str, end_date_str):
    start_date = datetime.strptime(start_date_str, '%Y-%m-%d')
    end_date = datetime.strptime(end_date_str, '%Y-%m-%d')
    
    # Calculate years
    years = end_date.year - start_date.year
    
    # Adjust years if we haven't reached anniversary month
    if (end_date.month, end_date.day) < (start_date.month, start_date.day):
        years -= 1
    
    # Calculate months
    months = end_date.month - start_date.month
    if end_date.day < start_date.day:
        months -= 1
    if months < 0:
        months += 12
        
    return years, months

# Load existing workbook
wb = load_workbook('employee_tenure_step1.xlsx')
ws = wb.active

# Add header for tenure description
ws.cell(row=1, column=5, value="Tenure").font = Font(bold=True)

# Calculate tenure for each employee
for row in range(2, ws.max_row + 1):
    start_date = ws.cell(row=row, column=2).value
    current_date = ws.cell(row=row, column=3).value
    
    years, months = calculate_tenure_components(start_date, current_date)
    
    # Add tenure description
    tenure_desc = f"{years} years, {months} months"
    ws.cell(row=row, column=5, value=tenure_desc)

# Adjust column width for tenure description
ws.column_dimensions['E'].width = 20

wb.save('employee_tenure_step2.xlsx')

The code above:

  • Creates a function to calculate tenure accurately
  • Loads our existing workbook and adds a new “Tenure” column
  • Computes tenure for each employee in years and months
  • Handles edge cases like different month lengths and partial months
  • Formats the output in a clear “X years, Y months” format

The calculate_tenure_components function works by:
1. Converting string dates to datetime objects
2. Computing the difference in years
3. Adjusting for cases where the current date falls before the anniversary day
4. Calculating remaining months while accounting for month boundaries

When you run this code, your Excel file will update to show:


The same table as before, but with an additional 'Tenure' column showing the duration of each employee's service.
Image By Author
 

The new tenure column clearly shows how long each employee has been with the company. For example, we can quickly see that John Smith has been with the company for 14 years and 11 months, while Sarah Davis is a more recent hire at 3 years and 1 month. 

Adding Service Milestone Predictions

For workforce planning, it’s useful to know when employees will reach their next major service milestones. Let’s add a feature that calculates upcoming milestone dates (5, 10, 15, or 20 years of service) for each employee. This helps identify and plan for upcoming work anniversaries.

 
# Block 3: Adding Next Service Milestone
from openpyxl import load_workbook
from openpyxl.styles import Font
from datetime import datetime
from dateutil.relativedelta import relativedelta  # For date arithmetic

def calculate_next_milestone(start_date_str):
    start_date = datetime.strptime(start_date_str, '%Y-%m-%d')
    milestones = [5, 10, 15, 20]  # Years of service milestones
    
    # Calculate years of service
    years_served = relativedelta(datetime.now(), start_date).years
    
    # Find next milestone
    next_milestone = next((m for m in milestones if m > years_served), None)
    if next_milestone:
        milestone_date = start_date + relativedelta(years=next_milestone)
        return f"{next_milestone}-Year: {milestone_date.strftime('%Y-%m-%d')}"
    return "All milestones achieved!"

# Load workbook
wb = load_workbook('employee_tenure_step2.xlsx')
ws = wb.active

# Add header for milestone column
ws.cell(row=1, column=6, value="Next Milestone").font = Font(bold=True)

# Calculate next milestone for each employee
for row in range(2, ws.max_row + 1):
    start_date = ws.cell(row=row, column=2).value
    milestone_info = calculate_next_milestone(start_date)
    ws.cell(row=row, column=6, value=milestone_info)

# Adjust column width
ws.column_dimensions['F'].width = 25

wb.save('employee_tenure_final.xlsx')

This final code block:

  • Uses relativedelta for precise date calculations
  • Identifies the next milestone (5, 10, 15, or 20 years) for each employee
  • Calculates the exact date when each milestone will be reached
  • Formats milestone dates consistently with other dates in the workbook

Here’s how the finished workbook looks with milestone predictions:


The previous table with an added 'Next Milestone' column, indicating upcoming work anniversaries (e.g., 5-year, 10-year, 15-year).
Image By Author
 

Looking at the results, we can see that:

  • Robert Brown will reach his 10-year milestone on 2025-09-20
  • Sarah Davis has her 5-year milestone coming up on 2027-01-10
  • John Smith’s next milestone is his 15-year anniversary on 2025-03-15

These milestone predictions help managers plan ahead for employee recognition events and track long-term retention metrics.

This completes our employee tenure tracking system. By combining Python’s date handling capabilities with openpyxl, we’ve created a tool that automatically calculates tenure and predicts future milestones for an entire workforce.

For additional Excel automation techniques using Python and openpyxl, check out our related guides on:

  1. How to Effectively Work with Excel Files in Python: Pandas vs Openpyxl Guide
  2. How to Implement Excel-Style Conditional Logic with Openpyxl
  3. How to Format Dates in Excel Using Python and Openpyxl

Leave a Reply

Your email address will not be published. Required fields are marked *