Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Power Query DateTime.IsInPreviousNHours: How-To Guide

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

The DateTime.IsInPreviousNHours function in Power Query is a specialized utility used to filter or flag data based on whether a specific datetime value falls within the last N hours from the current system time. It is particularly useful for creating dynamic reports that automatically update to show recent activity, such as the last 24 hours of sensor data or login attempts, without requiring manual date adjustments.

What You'll Need

  • Microsoft Excel or Power BI: Ensure you are using a version that supports Power Query (Excel 2016 or later, or any current Power BI Desktop version).
  • A Data Source with Datetime Columns: The column you intend to filter must be typed as datetime. Text or date-only columns will cause errors.
  • System Clock Accuracy: Since this function relies on the local machine's clock, ensure your computer’s time and timezone settings are correct.

Step-by-Step

  1. Load Your Data into Power Query: Open Excel or Power BI, go to the Data tab, and select Get Data. Choose your source (e.g., CSV, SQL Server) and load it into the Power Query Editor. Alternatively, if you already have a table in your workbook, select it and click Transform Data.
  2. Verify Column Type: Locate the column containing your timestamps. Click the icon next to the column header to check its type. If it says Any, Text, or Date, change it to DateTime by selecting Change Type > Using Locale or directly choosing DateTime from the dropdown. This step is critical because the function strictly requires a datetime object.
  3. Open the Advanced Editor (Optional but Recommended): While you can use the UI filters, writing the M code directly gives more control. Go to the Home tab and click Advanced Editor. Here you will see the underlying M script.
  4. Apply the Filter Using the Function: To filter rows where the timestamp is within the previous N hours, add a new step. For example, to keep only records from the last 5 hours, insert the following line after your source step:
    FilteredRows = Table.SelectRows(Source, each DateTime.IsInPreviousNHours([YourColumnName], 5))
    Replace Source with the name of your previous step and [YourColumnName] with the actual name of your datetime column.
  5. Or Use the UI Filter Menu: If you prefer not to write code, right-click the datetime column header. Select Filter > Custom Filter. However, note that standard custom filters do not expose DateTime.IsInPreviousNHours directly. You typically need to create a helper column first. Add a Custom Column named "IsRecent" with the formula:
    = DateTime.IsInPreviousNHours([YourColumnName], 5)
    This returns true or false. Then, filter this new column to keep only true values.
  6. Close and Apply: Once the filter is applied, click Close & Load (in Excel) or Close & Apply (in Power BI). The resulting table will now dynamically show only the records from the specified number of hours ago relative to when the query was refreshed.

Common Mistakes

  • Incorrect Data Type: The most frequent error occurs when the column is still recognized as text or date. Always explicitly set the column type to DateTime before applying the function.
  • Timezone Confusion: This function uses the local time of the machine running the query. If your data is stored in UTC but your machine is in EST, the results will be offset by several hours. You may need to convert your data to local time first using DateTimeZone.ToLocal or adjust the logic accordingly.
  • Hardcoding Values: Users often forget that the "N" in the function is static once written. If you want users to choose the number of hours, you should parameterize the query rather than hardcoding the integer.
  • Ignoring Refresh Timing: Because the function depends on the current time, the results change every time you refresh the query. If you need a static snapshot, you must capture the timestamp at load time instead of filtering dynamically.

Tips

  • Use Parameters for Flexibility: Create a parameter in Power Query named HoursToLookBack with a default value (e.g., 24). Reference this parameter in your filter step: each DateTime.IsInPreviousNHours([Column], HoursToLookBack). This allows end-users to change the lookback period without editing the M code.
  • Combine with Other Filters: You can chain multiple conditions in Table.SelectRows. For example, to find recent errors only, use and: each DateTime.IsInPreviousNHours([Timestamp], 2) and [Status] = "Error".
  • Performance Optimization: Filtering early in the query steps reduces the amount of data processed in subsequent transformations. Place the DateTime.IsInPreviousNHours filter as close to the source step as possible.
  • Testing Edge Cases: Test with boundary times (e.g., exactly N hours ago) to understand how the function handles inclusive vs. exclusive ranges. Generally, it includes times strictly greater than the cutoff point.

Troubleshooting

If the function does not return expected results, follow these checks:

  • Check for Nulls: If some rows have empty timestamps, the function might throw an error or exclude them unexpectedly. Wrap the call in try ... otherwise false or filter out nulls beforehand: Table.SelectRows(Source, each [Column] <> null).
  • Verify System Time: Compare the current time shown in your OS taskbar with the time returned by DateTime.LocalNow() in a temporary column. If they differ significantly, your system clock or timezone settings are incorrect.
  • Inspect the Error Message: If you see "Expression.Error: We cannot apply operator...", it usually means the data types are mismatched. Double-check that the argument passed to the function is indeed a datetime value and not a string representation of one.
  • Refresh Issues: If the data doesn't seem to update, ensure you are actually refreshing the query. In Excel, press Ctrl+Alt+F5 to force a full refresh. In Power BI, click the Refresh button in the ribbon.

Frequently Asked Questions

Does DateTime.IsInPreviousNHours account for daylight saving time?

No, it operates on the local system time. If your system adjusts for daylight saving time, the function will reflect that adjustment because it uses the current local clock. However, it does not inherently know about historical DST changes in the data unless the data itself contains timezone-aware datetime objects.

Can I use this function in Power BI Service?

Yes, but be cautious. When scheduled refreshes run in the cloud, the "current time" is determined by the gateway or service server, not your local machine. This can lead to unexpected results if there is a significant timezone difference between your location and the server location.

How do I include the exact moment N hours ago?

The function typically checks if the datetime is strictly greater than the current time minus N hours. To include the exact boundary, you might need to use a custom calculation like each [Column] >= DateTime.LocalNow() - #duration(0, N, 0, 0), which offers more precise control over inclusive/exclusive boundaries.

Why is my filtered table empty?

If your table is empty, check two things: First, ensure your data actually contains timestamps within the requested window. Second, verify that the column type is correctly set to DateTime. If the column is treated as text, the comparison fails silently or throws an error, depending on the context.