Private/ConvertFrom-PythonDate.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
function ConvertFrom-PythonDate {
    # Helper function that takes a string returned from a python datetime in the form of 2020-02-10T17:51:55.734794Z and converts it
    # to a PowerShell/.NET datetime object
    param(
        [Parameter(ValueFromPipeline = $true)]    
        [string]$Date = ''
    )

    begin {
        $Culture = [Globalization.CultureInfo]::InvariantCulture
    }
    process { 
        if ($null -ne $Date -and $Date -ne '') {
            # sometimes jokers use various date formats on the submitted indicators.
            # try yyyy-MM-ddTHH:mm:ss first (e.g.: 2020-02-12T08:12:23Z)
            try {
                # regardless whether we're given 0 digits of milliseconds or 6, always trim after seconds, tack on Zulu,
                # and move on with formatting
                Write-Output ([datetime]::ParseExact($Date.Substring(0, 19) + 'Z', 'yyyy-MM-ddTHH:mm:ssZ', $Culture))
            }
            catch { }
            # try MM/dd/yyyy HH:mm:ssZ (e.g.: 02/12/2020 08:12:23Z)
            try {
                # regardless whether we're given 0 digits of milliseconds or 6, always trim after seconds, tack on Zulu,
                # and move on with formatting
                Write-Output ([datetime]::ParseExact($Date.Substring(0, 19) + 'Z', 'MM/dd/yyyy HH:mm:ssZ', $Culture))
            }
            catch { }
            
        }  
    }

    end { }
}