DateTime.IsInPreviousNHours

Updated on

DateTime.IsInPreviousNHours is a Power Query M function that indicates whether the provided date(time) value occurs during the previous number of hours specified. The function returns true if the value occurs within the specified hours, otherwise false.

Compatible with: Power BI Service Power BI Desktop Excel Microsoft 365

Syntax

DateTime.IsInPreviousNHours(
   dateTime as any,
   hours as number,
) as nullable logical

Description

DateTime.IsInPreviousNHours indicates whether the given dateTime argument (which can be of type datetime or datetimezone) occurs during the previous number of hours, as determined by the current date and time on the system. This function will return false for a value within the current hour.

Examples

Let’s explore two examples to understand how the DateTime.IsInPreviousNHours function works.

Checking DateTime Values for the Previous N Hours

Imagine you have a table with DateTime values and you want to add a column that shows true for DateTime values that fall within the previous n hours. You can do this by using the DateTime.IsInPreviousNHours function on your [DateTime] column, where n is the number of hours you want to check.

// Output depends on [DateTime] column and n
DateTime.IsInPreviousNHours( [DateTime], n )

This expression returns true for any DateTime values in the [DateTime] column that fall within the previous n hours. For example, if you set n to 2, you would use the following code:

DateTime.IsInPreviousNHours( [DateTime], 2 )

If the current time is 10:29:13 PM on July 7, 2024, this function will return true for all rows with DateTime values between 8:00:00 PM and 9:59:59 PM. Here’s a screenshot that shows how this function can be used on a DateTime table that increments by 15 minutes each row:

Example of how to use the DateTime.IsInPreviousNHours Function in Power Query M

As the image shows, there are eight values that fall within the previous 2 hours.

Using the Current Date and Time

If you want to check with DateTime.IsInPreviousNHours if the current date and time falls within the previous few hours, you can do that using the DateTime.FixedLocalNow function and subtracting a number of hours using the #duration function:

// Output: true
DateTime.IsInPreviousNHours(
  DateTime.FixedLocalNow() - #duration(0, 3, 0, 0), 
  3
)

Other functions related to DateTime.IsInPreviousNHours are:

Contribute » | Contributors: Rick de Groot
Microsoft documentation: https://learn.microsoft.com/en-us/powerquery-m/datetime-isinpreviousnhours

2023-2024 © BI Gorilla. All rights are reserved. Information from Microsoft docs is property of Microsoft Corp. | Privacy Policy