在PowerShell中,如何将DateTime转换为UNIX时间?

在PowerShell中,如何将DateTime转换为UNIX时间?,datetime,powershell,Datetime,Powershell,在PowerShell中,如何将日期时间字符串转换为秒数之和 PS H:\> (New-TimeSpan -Start $date1 -End $date2).TotalSeconds 1289923177.87462 可以使用新的TimeSpan来实现这一点。比如说, $date1 = Get-Date -Date "01/01/1970" $date2 = Get-Date (New-TimeSpan -Start $date1 -End $date2).TotalSeconds

在PowerShell中,如何将日期时间字符串转换为秒数之和

PS H:\> (New-TimeSpan -Start $date1 -End $date2).TotalSeconds

1289923177.87462
可以使用新的TimeSpan来实现这一点。比如说,

$date1 = Get-Date -Date "01/01/1970"
$date2 = Get-Date
(New-TimeSpan -Start $date1 -End $date2).TotalSeconds
或者只使用这一行命令

(New-TimeSpan -Start (Get-Date "01/01/1970") -End (Get-Date)).TotalSeconds

为了获得自1970年以来不受时区影响的秒数,我将使用:

$unixEpochStart = new-object DateTime 1970,1,1,0,0,0,([DateTimeKind]::Utc)
[int]([DateTime]::UtcNow - $unixEpochStart).TotalSeconds

如前所述,UNIX时代是1970年1月1日凌晨12:00(午夜)UTC。 为了以整数形式获得自UTC纪元以来的当前秒数,我使用这个80字符的一行

$ED=[Math]::Floor([decimal](Get-Date(Get-Date).ToUniversalTime()-uformat "%s"))

上面的代码是符合PowerShell 2.0的&四舍五入(以确保与UNIX的行为一致)

为了避免2038年的问题,我建议使用以下代码,它基于滴答(Int64)而不是秒(Int32)。[数学]::使用Floor,因为Unix时间基于自纪元以来的整秒数

[long][Math]::Floor((($DateTime.ToUniversalTime() - (New-Object DateTime 1970, 1, 1, 0, 0, 0, ([DateTimeKind]::Utc))).Ticks / [timespan]::TicksPerSecond))

这一行适合我(与之相比)

几毫秒

[int64](([datetime]::UtcNow)-(get-date "1/1/1970")).TotalMilliseconds

在.NET Framework 4.6中,您可以使用
DateTimeOffset
类的方法:

[DateTimeOffset]::Now.ToUnixTimeSeconds()

$DateTime = Get-Date #or any other command to get DateTime object
([DateTimeOffset]$DateTime).ToUnixTimeSeconds()

以下cmdlet将windows正常运行时间转换为Unix时间格式:

   $s=Get-WmiObject win32_operatingsystem | select csname,@{LABEL='LastBootUpTime';EXPRESSION{$_.ConverttoDateTime($_.lastbootuptime)}};
   [Math]::Floor([decimal](Get-Date($s.LastBootUpTime.ToUniversalTime()).ToUniversalTime()-uformat "%s"))
再次与上面的其他人进行比较并在此基础上继续发展

$date1 = (Get-Date -Date "01/01/1970").ToUniversalTime()
$date2 = (Get-Date).ToUniversalTime()
$epochTime = [Math]::Floor((New-TimeSpan -Start $date1 -End $date2).TotalSeconds)

我只是想提出另一种,希望更简单的方法来解决这个问题。以下是我用来获取当前Unix(历元)UTC时间的一行代码:

$unixTime = [long] (Get-Date -Date ((Get-Date).ToUniversalTime()) -UFormat %s)
从内到外分解: (获取日期)。ToUniversalTime() 这将获取UTC时区中的当前日期/时间。如果你想知道当地时间,只需拨打GetDate。 然后将其用作…的输入

[长](获取日期-日期(UTC日期/时间自上面)-格式%s) 将UTC日期/时间(从第一步开始)转换为Unix格式。 -UFormat%s告诉Get Date以Unix历元时间的形式返回结果(从1970年1月1日00:00:00起已过几秒)。请注意,这将返回一个双精度数据类型(基本上是十进制)。通过将其强制转换为长数据类型,它会自动转换(舍入)为64位整数(无小数)。如果您想要十进制的额外精度,请不要将其转换为长类型

额外学分 将十进制数转换为整数的另一种方法是使用System.Math:


这里有一个脚本,我已经使用了一段时间(更长时间,因为它是为“新脚本”类型的人群编写的,带有各种注释),它可以在CTIME之间进行转换

# Here's a very quick variant to 'get the job done'
[Int64]$ctime=1472641743
[datetime]$epoch = '1970-01-01 00:00:00'
[datetime]$result = $epoch.AddSeconds($Ctime)

write-host $result

# A few example values for you to play with:
# 1290100140 should become ... 2010-11-18 17:09:00.000
# 1457364722 should become ... 2016-03-07 15:32:02.000
# 1472641743 should become ... 31/08/2016 11:09:03

# For repeated use / calculations, functions may be preferable. Here they are.

# FROM C-time converter function
# Simple function to convert FROM Unix/Ctime into EPOCH / "friendly" time
function ConvertFromCtime ([Int64]$ctime) {
    [datetime]$epoch = '1970-01-01 00:00:00'    
    [datetime]$result = $epoch.AddSeconds($Ctime)
    return $result
}

# INTO C-time converter function
# Simple function to convert into FROM EPOCH / "friendly" into Unix/Ctime, which the Inventory Service uses.
function ConvertToCTime ([datetime]$InputEpoch) {
    [datetime]$Epoch = '1970-01-01 00:00:00'
    [int64]$Ctime = 0

    $Ctime = (New-TimeSpan -Start $Epoch -End $InputEpoch).TotalSeconds
    return $Ctime
}

希望这能有所帮助,特别是如果你只是想让初学者更友好一点:)。

这一条也应该有效,因为javascript使用毫秒作为起始时间:

ConvertTo-Json (Get-Date) | ? { $_ -Match '\(([0-9]+)\)' } | % { $Matches[1]/1000 }
逐步:

PS P:\> Get-Date

lundi 15 janvier 2018 15:12:22


PS P:\> ConvertTo-Json (Get-Date)
{
    "value":  "\/Date(1516025550690)\/",
    "DisplayHint":  2,
    "DateTime":  "lundi 15 janvier 2018 15:12:30"
}

PS P:\> (ConvertTo-Json (Get-Date)) -Match '\(([0-9]+)\)'
True
PS P:\> $Matches

Name                           Value
----                           -----
1                              1516025613718
0                              (1516025613718)
动力壳

$epoch = (Get-Date -Date ((Get-Date).DateTime) -UFormat %s)

不确定何时添加了-uformat来获取日期,但它允许您使用unix日期格式字符串

[int64](get-date -uformat %s)

您可以使用get date的Uformat参数。但首先我想确定一个给定工作站的日期是正确的(我认为工作站连接到一个公司网络,那里有一个服务器设置了正确的时间)。 然后,我获取实际的unix时间戳,以比较实际日期和创建日期之间的对象(帐户)(unix时间戳超过限制日期时的帐户删除任务)


为了向Grafana发送数据,我需要Unix历元时间作为UTC的32位整数。最终的最佳解决方案是:

$unixtime = (get-date -Date (get-date).ToUniversalTime() -UFormat %s).Substring(0,10)
这将生成一个字符串,但可以轻松转换为整数:

[int]$unixtime = (get-date -Date (get-date).ToUniversalTime() -UFormat %s).Substring(0,10)
我在Ubuntu机器上测试了这个。上面的命令和Linux命令的结果

date +%s
答案相同。

迟交的答案

Hare都是转换函数
convertToUnixtime
&
convertFromUnixtime
,以方便使用(都支持流水线)

函数convertfromunixtime(){ [CmdletBinding()] param( [参数(必需,ValueFromPipeline,位置=0)] [Int64]$UnixTime ) 开始{ $epoch=[DateTime]::指定索引('1970-01-01','Utc') } 过程{ $epoch.AddSeconds($UnixTime) } } 函数转换为UnixTime{ [CmdletBinding()] param( [参数(必需,ValueFromPipeline,位置=0)] [DateTime]$DateTime ) 开始{ $epoch=[DateTime]::指定索引('1970-01-01','Utc') } 过程{ [Int64]($DateTime.ToUniversalTime()-$epoch).TotalSeconds } }
一个独立于文化的、实际上非常快速的答案:

[int64]([double]::Parse((get-date -uformat "%s"),[cultureinfo][system.threading.thread]::currentthread.currentculture))
当它实际生成格式化字符串时,它会调用一些.NET“魔法”,使用当前线程的区域性设置将其转换为double,然后转换为int64,默认情况下,int64正好执行提供的double。如果需要UTC时间戳,请在
get date
中使用
-date([DateTime]::UtcNow)
将当前UTC时间用作转换时间

[int64]([double]::Parse((get-date -date ([DateTime]::UtcNow) -uformat "%s"),[cultureinfo][system.threading.thread]::currentthread.currentculture))
PS:除非你真的需要一个字符串作为你的输出,否则拥有一个整数对你的编程文化来说总的来说更好。

对我来说有点冗长。我是这样做的:

[int] (Get-Date (Get-Date).ToUniversalTime() -uformat '%s')

你说的“秒之和”是什么意思?UNIX时间(从纪元算起的秒数)?是的,我指的是UNIX时间Get Date和[System.DateTime]之间有什么区别?在我的应用程序中,我使用了[System.DateTime]。没什么,好吧。Get Date等于[DateTime]::Now和Get Date-日期“01/01/1970”等于[DateTime]::Parse(“01/01/1970”)Unix时间基于UTC,因此最后一行应使用$date2.ToUniversalTime()。用[int]作为前缀也很有用。它们不是都是UTC吗?如果是这样的话,同一时区的两个日期时间对象之间的距离会有差异吗?请检查此答案-如果您使用的是PS 5.1,请注意我的#亡灵巫师徽章来自此答案。很高兴大家都喜欢它:)这在我的Powershell v3中肯定没有给出正确的UNIX时间戳(既不是秒也不是毫秒)。我不知道这怎么会得到这么多选票@拉兹列夫,你可能误读了;上面的代码在PowerShell v2、v3和v4中返回一个与UNIX兼容的“秒数”(UTC中的1970年1月1日)。我刚刚确认了这一点。请记住,80字符一行程序将值存储在变量中,因此它不是
date +%s
[int64]([double]::Parse((get-date -uformat "%s"),[cultureinfo][system.threading.thread]::currentthread.currentculture))
[int64]([double]::Parse((get-date -date ([DateTime]::UtcNow) -uformat "%s"),[cultureinfo][system.threading.thread]::currentthread.currentculture))
[int] (Get-Date (Get-Date).ToUniversalTime() -uformat '%s')