Calculate the difference between two times in python

I am using python and want to calculate the difference between two points.

Actually, I had a script for calculating the difference between the login and logout times, for example, in organizations there is a certain limit for working hours, so if a user is registered at 9:00 AM in the morning, and if he leaves in the evening at 6:00 PM in the evening, we need to calculate how much time he left in the office (which corresponds to 9 hours in this scenario), but I want to do it in python, so someone please let me know how to achieve the above concept of calculating the difference between time login and logout?

+6
source share
4 answers
 >>> start = datetime.datetime(year=2012, month=2, day=25, hour=9) >>> end = datetime.datetime(year=2012, month=2, day=25, hour=18) >>> diff = end - start >>> diff datetime.timedelta(0, 32400) >>> diff.total_seconds() 32400 >>> diff.total_seconds() / 60 / 60 9 >>> 
+19
source

use divmod for this task

 >>> start = datetime.datetime.utcnow() >>> end = datetime.datetime.utcnow() >>> divmod(end - start, 60) (0, 2.454) # (minutes, seconds) 

divmod will give

+3
source

In my opinion @Fabian's answer is probably the best. But are we making it more complicated than it should be?

Do you need to calculate it by days, months, years?

If you create this, wouldn't it be easier to use the timesec view?

When a user logs in:

 user_login_time = time.time() 

When the user revises:

 time_difference = time.time() - user_login_time 

Then check if the time_difference is more than XXXX seconds longer? Now I assume that you are just going to check if the user has not been registered for XX minutes or xx hours?

Otherwise, I would like to emphasize that @Fabian's answer would be better if you are looking at parsing time strings, or you need to perform other time and date functions with data.

I would also like to emphasize that if you use this method to create constants for time or do not forget to comment on them to make it more readable.

But if you're just trying to figure out if the user has been logged on in the last 30 minutes, it might be easier.

+2
source

You are using the wrong classes to represent time in the first place.

 > import datetime > print datetime.datetime.now() - datetime.datetime(2013, 1, 1) 55 days, 14:11:06.749378 

The returned object is timedelta . But the difference, of course, is calculated between datetime objects.

+1
source

All Articles