How to Subtract Time in PowerShell (With Examples)


You can use the following basic syntax in PowerShell to subtract a specific amount of time from a datetime variable:

$my_time - [timespan]'2:10:15'

This particular example subtracts 2 hours, 10 minutes and 15 seconds from the datetime stored in the variable named $my_time.

Note that if you only want to subtract a certain amount of hours from a datetime variable, then you could simply this to the following:

$my_time - [timespan]'2:0'

This particular example subtracts 2 hours from the datetime stored in the variable named $my_time.

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

Example: How to Subtract Time in PowerShell

Suppose that we use the following syntax to create a datetime variable that contains the current date and time that this article is being written:

$my_time - Get-Date

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

We can see that the $my_time variable contains the following datetime:

  • 3/14/2024 8:51:56 AM

Suppose that we would like to subtract 2 hours, 10 minutes and 15 seconds from this datetime.

We can use the following syntax to do so:

$my_time - [timespan]'2:10:15'

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

PowerShell subtract time from datetime

We can see that this returns the following datetime:

  • 3/14/2024 6:41:41 AM

We have successfully subtracted 2 hours, 10 minutes and 15 seconds from the original datetime variable.

Note that if we’d like to only subtract 2 hours, we could use the following syntax instead:

$my_time - [timespan]'2:0'

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

PowerShell subtract hours from datetime

We can see that this returns the following datetime:

  • 3/14/2024 6:58:20 AM

We have successfully subtracted 2 hours from the original datetime variable.

Feel free to use any combination of hours, minutes and seconds that you would like when subtracting time from your own variable in PowerShell.

Note: To add time to an existing datetime variable, simply change the subtraction sign to an addition sign in the formula.

Related Tutorials

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

How to Compare Dates in PowerShell
How to Get Date Without Time in PowerShell
How to Calculate Date Difference in PowerShell

Leave a Reply