DEV Community

Murabyte
Murabyte

Posted on Edited on

Merge duplicate attendance punches in pandas before you take first in and last out

Disclosure: I make PunchSheet at Murabyte, which is mentioned at the end. Written with AI assistance and reviewed by Murabyte.

Attendance devices often log the same tap twice within a few seconds. If you take "first punch in, last punch out" without cleaning those, one extra row can hide a real check-out. Here is a small pandas routine that merges near-duplicate punches first.

The input

One row per punch: employee ID and a timestamp.

import pandas as pd

df = pd.read_csv("punches.csv", parse_dates=["timestamp"])
df = df.sort_values(["employee_id", "timestamp"]).reset_index(drop=True)
Enter fullscreen mode Exit fullscreen mode

Drop punches that follow the previous one too closely

gap = df.groupby("employee_id")["timestamp"].diff()
clean = df[gap.isna() | (gap > pd.Timedelta(minutes=2))]
Enter fullscreen mode Exit fullscreen mode

The first punch of each employee has no previous row, so its gap is empty and it is kept. Anything within 2 minutes of the previous punch is treated as a double tap. Choose the window that fits your device.

One row per employee per day

clean = clean.assign(day=clean["timestamp"].dt.date)
daily = clean.groupby(["employee_id", "day"])["timestamp"].agg(
    first_in="min", last_out="max", punches="count"
)
daily["single_punch"] = daily["punches"] == 1
Enter fullscreen mode Exit fullscreen mode

Rows where single_punch is true are missing a check-in or check-out. Send them to the manager instead of counting them as zero hours.

Night shifts

If a shift crosses midnight, shift the timestamps back by a few hours (for example 4) before taking the date, so the whole shift lands on the day it started. Check one employee by hand after changing it.

Doing it without code

PunchSheet is a Windows app that does these steps offline. It loads device exports (CSV, TXT, DAT, XLS, XLSX), detects the columns, handles shifts and several devices, and exports colored daily and monthly Excel reports. No account and no uploads. It is $49 one time, and the license key works on 2 PCs. The free trial opens your files and shows the on-screen preview; exporting the Excel report needs the license key.

Free trial: https://murabyte.gumroad.com/l/punchsheet-trial
Gumroad: https://murabyte.gumroad.com/l/punchsheet
Microsoft Store: https://apps.microsoft.com/detail/9N8MT2L4CSDS

python #pandas #excel #hr

Written with AI assistance and reviewed by Murabyte.

Top comments (0)