Date and Time
Learn about date and time in Python and Powershell.
We'll cover the following...
Get date and time
Let’s begin by understanding how to retrieve date and time information.
System.DateTime
Getting date and time in PowerShell is done using the cmdlet Get-Date or using the [datetime] type accelerator.
### date and timeGet-date[datetime]::Now | Format-List[datetime]::Now # local time[datetime]::UtcNow # time in UTC
Under the hood, both methods call .net class’ System.DateTime to return rich DateTime objects. If we dig a little deeper, we’ll see that there is no difference at all in the returned objects.
[datetime].FullName
(Get-Date).GetType().FullName
If we pipe the results of the Get-Date cmdlet to Get-Member, we will find the member properties and methods of the DateTime object like Day, Hour, Minute, Second, AddDays(), and AddHours().
Get-Date | Get-Member
These properties can be utilized to get the current date and time:
## using date time properties## just date, time defaults to midnight(Get-Date).Date## date and time(Get-Date).DateTime## time of the day(Get-Date).TimeOfDay## other properties(Get-Date).Day(Get-Date).Hour(Get-Date).Minute(Get-Date).Year
Methods of class System.DateTime time objects can be used to perform various date-time operations like adding years, hours, or minutes to the current date.
## using date time methods
(Get-Date).AddYears(2) # current year + ...