简体   繁体   中英

Excel Calculate time in time blocks

How do I calculate a time difference between 2 date, but splitted in "Day" and "Night" hours.

Example:

"Day" hours are defined between 07:00 and 21:00 (14h)

"Night" hours are defined between 21:01 and 06:59 (10h)

I have now following start/end times with expected results:

  • 20.04 10:00 / 20.04 14:00 => day 4h / night 0h
  • 20.04 20:00 / 20.04 22:00 => day 1h / night 1h
  • 20.04 22:00 / 21.04 05:00 => day 0h / night 7h
  • 19.04 00:00 / 21.04 24:00 => day 42h / night 30h

How to calculate that simply ?

Here's a relatively mundane solution.

First of all, you probably know that the datetime in Excel is a number and that integer numbers are the ones representing midnights. But if you didn't, well the things below would make zero sense, so I am making sure.

We will compute day hours first, then get night hours from that since day hours are a little more intuitive to compute. We'll do that by getting the interval containing "completely covered days" - then every such a day contributes 21 - 7 = 14 hours to the result. Then we'll add the hours lost due to the first "late" day and the last "early leaving" one.

Please note that if the parameter interval is in the middle of one day (like your first example), this will get "reversed" interval of "covered" days. This is not really a bug, although it might be a little confusing - the end result is correct.

Anyway, here's a frankenformula for day hours, assuming you store your parameter interval endpoints in B1 and B2, and the first one is earlier.

=(IF(B2-INT(B2)>21/24,1,0)+INT(B2)-(IF(B1-INT(B1)<7/24,0,1)+INT(B1)))*(21-7)+IF(AND(B1-INT(B1)>7/24,B1-INT(B1)<21/24),24*((21/24)-B1+INT(B1)),0)+IF(AND(B2-INT(B2)>7/24,B2-INT(B2)<21/24),24*(B2-INT(B2)-(7/24)),0)

I would however strongly recommend looking up what does it do, here's a version that is easier to analyze (it got translated to Polish though, hopefully it will get translated back when you download it and open in Excel or something).

EDIT: Excel Online doesn't want to publicly display dates as dates for some reason. Again, consider downloading the spreadsheet (and giving it a virus check, if you wish to).

I think you'd need to convert the time values to number values, then use a helper column for your "target" times IE 21:01, 06:59 then perform a count and greater than less than formula.

Sorry to be a little vague but its difficult to be exact with the data above - are you able to share the file?

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