Calculate the difference between two times in python

隐身守侯 提交于 2019-12-09 16:48:35

问题


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

Actually i had scenario to calculate the difference between login and logout times, for example in organizations there is some particular limit for working hours, so if a user login at 9:00 AM in the morning and if he logs out at 6:00 PM in the evening, we need to calculate how much duration he stayed in the office(which is 9 hours in the present scenario ), but i want to do this in python, so can anyone please let me know how to achieve the above concept of calculating the difference between login and logout times ?


回答1:


>>> 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
>>> 



回答2:


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:


In my opinion @Fabian's answer is probably the best. But are we making this more difficult than it has to be?

Do you need to calculate it by day, month, year?

If you are generating this, wouldn't it be easier to just use a timesec representation?

When a user logins in:

user_login_time = time.time()

When the user revisits:

time_difference = time.time() - user_login_time

Then check to see if the time_difference is above XXXX seconds? now I am assuming that you are just going to check if the user hasn't logged in XX minutes, or xx hours?

Otherwise, I would stress that @Fabian's answer would be the best, if you are looking at parsing time date strings, or needing to do other time/date functions with the data.

I would also stress, that if you use this method, to make constants for the times, or make sure to comment them, to make it more readable.

But if your simply just trying to find out if the user has been on within the last 30 minutes, this might be easier.




回答4:


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 a timedelta. But the difference is of course computed between datetime objects.



来源:https://stackoverflow.com/questions/15067710/calculate-the-difference-between-two-times-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!