Skip to content
Advertisement

Best way to store attendance and get difference of time in MySQL?

I’m very new to the SQL language and MySQL. I’m working on a little Time and Attendance application IN PYTHON. What it does is logs the clock in and out time. Then calculates the hours worked and returns the amount according to the time worked.

What I want to know is the best way to store these clock in and clock out times and how to get the time difference?

So far, I’ve made a table for the employees as follows:

Here the join_date is the creation of this employee and the rest I’m guessing is self explanatory.

I 2 things in mind. It was to either make two separate tables, one for clocking in and one for clocking out. Then getting calculating and returning the time worked in Python. For this, I don’t know how to get the verify the employee_id in these tables. Do I use the INNER JOIN or the FOREIGN KEY.

or, I could have only one table that will have the clock in and clock out columns but I still don’t know how to verify the employee_id.

I know that the start_time would be TIMESTAMP DEFAULT CURRENT_TIMESTAMP but when I goto update the clock out time, wouldn’t this be updated again?

I am lost. Please help me, this is very painful. I can’t find my answers anywhere. Thanks,

Advertisement

Answer

The way forward here is to create a separate table to store the start and finish times in. You can store them either as integers (and use Unix timestamps), or, better still, store them as MySQL datetime types – this way you can use function in MySQL, such as TIMESTAMPDIFF.

Then, link each row to the appropriate employee using a foreign key reference to the employee_id column on the employees table.

The above is probably pseudo code as I’m a beer into my evening 🙂

I’ve made the table a bit smarter by using a stored virtual column to hold the TIMESTAMPDIFF value. This way you won’t need to pull data into your application to calculate the length of each session; let the database do the work! Just watch out for timezones…

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement