Dicky Raambo
Dicky Raambo

Reputation: 523

add +1 hour to datetime.time() django on forloop

I have code like this, I want to check in the time range that has overtime and sum it.

currently, am trying out.hour+1 with this code, but didn't work.


    overtime_all = 5
    overtime_total_hours = 0
    out = datetime.time(14, 30)

    while overtime_all > 0:
        overtime200 = object.filter(time__range=(out, out.hour+1)).count()
        overtime_total_hours = overtime_total_hours + overtime200
        overtime_all -=1

    print overtime_total_hours

how to add 1 hour every loop?...

Upvotes: 2

Views: 3142

Answers (2)

Dicky Raambo
Dicky Raambo

Reputation: 523

I found the solution now, and this is work.


    overtime_all = 5
    overtime_total_hours = 0
    out = datetime.time(14, 30)

    while overtime_all > 0:
        overtime200 = object.filter(time__range=(out,datetime.time(out.hour+1, 30))).count()
        overtime_total_hours = overtime_total_hours + overtime200
        overtime_all -=1

    print overtime_total_hours

i do change out.hour+1 to datetime.time(out.hour+1, 30) its work fine now, but i dont know maybe there more compact/best solution.

thank you guys for your answer.

Upvotes: 1

Guybrush
Guybrush

Reputation: 2780

Timedelta (from datetime) can be used to increment or decrement a datatime objects. Unfortunately, it cannot be directly combined with datetime.time objects.

If the values that are stored in your time column are datetime objects, you can use them (e.g.: my_datetime + timedelta(hours=1)). If they are time objects, you'll need to think if they represent a moment in time (in that case, they should be converted to datetime objects) or a duration (in that case, it's probably easier to store it as an integer representing the total amount of minutes, and to perform all operations on integers).

Upvotes: 1

Related Questions