最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

powerbi - How to calculate exact hours between 2 dates excluding weekends? - Stack Overflow

programmeradmin1浏览0评论

I need to calculate the exact hours between 2 dates which is in the format of mm/dd/yyyy hh:mm:ss. Both the columns having same format. I should exclude the weekends only and no holidays as we are 24/5.

Opened Date Closed Date
1/4/2025 10:30:55 1/7/2025 12:30:55
1/10/2025 1:30:55 1/15/2025 15:30:55

I need to calculate the exact hours between 2 dates which is in the format of mm/dd/yyyy hh:mm:ss. Both the columns having same format. I should exclude the weekends only and no holidays as we are 24/5.

Opened Date Closed Date
1/4/2025 10:30:55 1/7/2025 12:30:55
1/10/2025 1:30:55 1/15/2025 15:30:55

I have added the another calender table and performed the datesbetween. However i got the result in days. I want to more specific on hours.

Share Improve this question edited Jan 31 at 6:35 DarkBee 15.6k8 gold badges72 silver badges117 bronze badges asked Jan 31 at 4:12 Deepak DDeepak D 1
Add a comment  | 

2 Answers 2

Reset to default 0

You just need to change this line: RETURN DATEDIFF(StartHour, EndHour, HOUR)

to

RETURN DATEDIFF(StartHour, EndHour, MINUTE)

If you wanted to a fractional hour, you'd divide by 60 RETURN DIVIDE(DATEDIFF(StartHour, EndHour, MINUTE),60)

Working24x5Hours =
 VAR StartDateTime = 'Table'[Opened Date]
 VAR EndDateTime = 'Table'[Closed Date]

 -- Convert Start and End Date to only dates for filtering workdays
VAR StartDate = DATEVALUE(StartDateTime)
VAR EndDate = DATEVALUE(EndDateTime)

-- Table of workdays (Monday-Friday) between start and end dates
 VAR WorkDays =
  FILTER(
    ADDCOLUMNS(
        CALENDAR(StartDate, EndDate),
        "Weekday", WEEKDAY([Date], 2),  -- Monday = 1, Sunday = 7
        "IsFirstDay", [Date] = StartDate,
        "IsLastDay", [Date] = EndDate
    ),
    [Weekday] <= 5  -- Exclude Saturday (6) & Sunday (7)
)

 -- Calculate exact working hours per day
 VAR TotalHours =
  SUMX(
    WorkDays,
    VAR CurrentDate = [Date]
    VAR IsFirst = [IsFirstDay]
    VAR IsLast = [IsLastDay]
    
    VAR StartHour = IF(IsFirst, StartDateTime, CurrentDate & " 00:00:00")
    VAR EndHour = IF(IsLast, EndDateTime, CurrentDate & " 23:59:59")
    
    RETURN DATEDIFF(StartHour, EndHour, HOUR)
)

    RETURN TotalHours
  • Identifies only weekdays
  • Handles cases where the start and end date fall on the same day
  • Correctly calculates for multi-day durations

Here is how it works For 1/4/2025 10:30:55 to 1/7/2025 12:30:55

  • 1/4 (Saturday) & 1/5 (Sunday) ignored
  • 1/6 (Monday): 24 hours
  • 1/7 (Tuesday): 12.5 hours

Total: 50 hours

发布评论

评论列表(0)

  1. 暂无评论