简体   繁体   中英

Business time difference between datetime objects in Python

How do I find the business time difference between two datetime objects in Python?

Business time can be 9-17

I want also to consider holidays. I have a function is_holiday(date) that takes a date object.

def buisiness_time_between(datetime1, datetime2):
    return business_time_after(datetime1) +
        (business_time_per_day * days_between(datetime1,datetime2)) +  
        business_time_before(datetime2)

I'm sure you can figure out how to implement business_time_after , business_time_before , business_time_per_day , and days_between

I did not really find a simple pythonic answer to this problem.

The package businesstime suggested by JF Sebastian does what I wanted, but I think that the algorithms can be optimized and simplified. For example, if we change the model of the day we can use the standard python datetime operations.

I try to be clearer : if our work day is 9-17 we may say that our day is made by 8h and not 24h. So, 9:00->0:00 and 17:00->08:00. Now what we have to do is to create a function that converts the real time inside our new model in this way:

  • if it is a time lower than our start time (09:00), we don't care about it and we convert it to 00:00
  • if it is a business time we convert subtracting the start time, for example 13:37 becomes 04:37
  • if it is a time greater than our stop time (17:00), we don't care about it and we convert it to 08:00

After this conversion all the calculation can be made easily with the python datetime package as you do with a normal datetime.

Thanks also to the answer of user2085282 you can find this concept implemented in the repo django-business-time .

With the model conversion, I found extremely easy to add another feature: the lunch break

In fact, if you have a lunch break 12-13, you can map in your new day model all the times inside the interval to 12. But pay attention to convert also the time after 13 considering one hour of lunch break.

I am sorry that what I developed is just a Django application and not a Python package. But for the moment, it works for me. And sorry also for my code, I am a newbie :)

PS: the full documentation is coming soon!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM