How to Calculate Time Difference in PowerShell


You can use the following syntax in PowerShell to calculate the difference between two times:

$file1 = (Get-ChildItem data1.csv).LastWriteTime
$file2 = (Get-ChildItem data2.csv).LastWriteTime
$time_diff = $file2 - $file1

This particular example calculates the difference between the last modified times of the files named data1.csv and data2.csv and stores the results in a variable named $time_diff.

We can then use the following syntax to return the time difference in hours, minutes, seconds, and milliseconds:

$time_diff.TotalHours
$time_diff.TotalMinutes
$time_diff.TotalSeconds
$time_diff.TotalMilliseconds

The following example shows how to use this syntax in practice.

Example: How to Calculate Time Difference in PowerShell

Suppose that we would like to calculate the difference between the last modified time of the following two files in our current directory:

  • nba_data.csv
  • mlb_data.csv

We can use the following syntax to extract the last modified time of each file and then store the difference between these two times in a variable named $time_diff:

$file1 = (Get-ChildItem nba_data.csv).LastWriteTime
$file2 = (Get-ChildItem mlb_data.csv).LastWriteTime
$time_diff = $file2 - $file1

The following screenshot shows how to use this syntax in practice:

PowerShell calculate time difference

The new $time_diff variable contains the time difference between the last modified times of these two files.

We can then use the following syntax to extract the difference between the times in terms of hours, minutes, seconds and milliseconds:

$time_diff.TotalHours
$time_diff.TotalMinutes
$time_diff.TotalSeconds
$time_diff.TotalMilliseconds

The following screenshot shows how to use this syntax in practice:

From the output we can see:

  • The difference between the two times in hours is 0.827 hours.
  • The difference between the two times in minutes is 49.646 minutes.
  • The difference between the two times in seconds is 2,978 seconds.
  • The difference between the two times in milliseconds is 2,978,781 milliseconds.

And so on.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Convert Unix Timestamp to Datetime
PowerShell: How to Convert Date to UTC Time
PowerShell: How to Subtract Time

Leave a Reply