如何将一个unix时间戳(自epoch以来的秒)转换为Ruby DateTime?

时间:2021-10-23 11:27:18

How do you convert a Unix timestamp (seconds since epoch) to Ruby DateTime?

如何将一个Unix时间戳(自epoch以来的秒)转换为Ruby DateTime?

6 个解决方案

#1


277  

DateTime.strptime can handle seconds since epoch. The number must be converted to a string:

DateTime。strptime可以处理自epoch以来的秒数。数字必须转换为字符串:

require 'date'
DateTime.strptime("1318996912",'%s')

#2


551  

Sorry, brief moment of synapse failure. Here's the real answer.

抱歉,是synapse失败的短暂瞬间。这是真正的答案。

require 'date'

Time.at(seconds_since_epoch_integer).to_datetime

Brief example (this takes into account the current system timezone):

简单示例(考虑到当前系统时区):

$ date +%s
1318996912

$ irb

ruby-1.9.2-p180 :001 > require 'date'
 => true 

ruby-1.9.2-p180 :002 > Time.at(1318996912).to_datetime
 => #<DateTime: 2011-10-18T23:01:52-05:00 (13261609807/5400,-5/24,2299161)> 

Further update (for UTC):

进一步更新(UTC):

ruby-1.9.2-p180 :003 > Time.at(1318996912).utc.to_datetime
 => #<DateTime: 2011-10-19T04:01:52+00:00 (13261609807/5400,0/1,2299161)>

Recent Update: I benchmarked the top solutions in this thread while working on a HA service a week or two ago, and was surprised to find that Time.at(..) outperforms DateTime.strptime(..) (update: added more benchmarks).

最近的更新:我在一两个星期前处理HA服务的时候,在这个线程中对顶部的解决方案进行了基准测试,并且很惊讶地发现Time.at(..)超过了DateTime.strptime(..)(更新:添加了更多的基准)。

# ~ % ruby -v
#  => ruby 2.1.5p273 (2014-11-13 revision 48405) [x86_64-darwin13.0]

irb(main):038:0> Benchmark.measure do
irb(main):039:1*   ["1318996912", "1318496912"].each do |s|
irb(main):040:2*     DateTime.strptime(s, '%s')
irb(main):041:2>   end
irb(main):042:1> end

=> #<Benchmark ... @real=2.9e-05 ... @total=0.0>

irb(main):044:0> Benchmark.measure do
irb(main):045:1>   [1318996912, 1318496912].each do |i|
irb(main):046:2>     DateTime.strptime(i.to_s, '%s')
irb(main):047:2>   end
irb(main):048:1> end

=> #<Benchmark ... @real=2.0e-05 ... @total=0.0>

irb(main):050:0* Benchmark.measure do
irb(main):051:1*   ["1318996912", "1318496912"].each do |s|
irb(main):052:2*     Time.at(s.to_i).to_datetime
irb(main):053:2>   end
irb(main):054:1> end

=> #<Benchmark ... @real=1.5e-05 ... @total=0.0>

irb(main):056:0* Benchmark.measure do
irb(main):057:1*   [1318996912, 1318496912].each do |i|
irb(main):058:2*     Time.at(i).to_datetime
irb(main):059:2>   end
irb(main):060:1> end

=> #<Benchmark ... @real=2.0e-05 ... @total=0.0>

#3


38  

Time Zone Handling

时区处理

I just want to clarify, even though this has been commented so future people don't miss this very important distinction.

我只是想澄清一下,尽管这已经被评论过了,所以未来的人们不会错过这个非常重要的区别。

DateTime.strptime("1318996912",'%s') # => Wed, 19 Oct 2011 04:01:52 +0000

displays a return value in UTC and requires the seconds to be a String and outputs a UTC Time object, whereas

在UTC中显示返回值,并要求秒为字符串并输出UTC时间对象,而。

Time.at(1318996912) # => 2011-10-19 00:01:52 -0400

displays a return value in the LOCAL time zone, normally requires a FixNum argument, but the Time object itself is still in UTC even though the display is not.

在本地时区中显示一个返回值,通常需要一个FixNum参数,但是时间对象本身仍然在UTC中,即使显示不是。

So even though I passed the same integer to both methods, I seemingly two different results because of how the class' #to_s method works. However, as @Eero had to remind me twice of:

因此,即使我将相同的整数传递给了这两种方法,但由于类的#to_s方法的工作方式,我似乎得到了两个不同的结果。然而,@Eero不得不提醒我两次:

Time.at(1318996912) == DateTime.strptime("1318996912",'%s') # => true

An equality comparison between the two return values still returns true. Again, this is because the values are basically the same (although different class's, the #== method takes care of this for you), but the #to_s method prints drastically different strings. Although, if we look at the strings, we can see they are indeed the same time, just printed in different time zones.

两个返回值之间的相等比较仍然返回true。同样,这是因为这些值基本上是相同的(尽管不同的类,#==方法为您处理了这个问题),但是#to_s方法打印了截然不同的字符串。尽管,如果我们看一下字符串,我们可以看到它们确实是同时出现的,只是在不同的时区里打印出来的。

Method Argument Clarification

方法参数说明

The docs also say "If a numeric argument is given, the result is in local time." which makes sense, but was a little confusing to me because they don't give any examples of non-integer arguments in the docs. So, for some non-integer argument examples:

文档还说“如果给出了一个数字参数,结果是在本地时间。”这是有意义的,但对我来说有点困惑,因为他们没有给出文档中任何非整数参数的例子。对于一些非整数的参数例子:

Time.at("1318996912")
TypeError: can't convert String into an exact number

you can't use a String argument, but you can use a Time argument into Time.at and it will return the result in the time zone of the argument:

您不能使用字符串参数,但是可以将时间参数用于时间。它将在参数的时区返回结果:

Time.at(Time.new(2007,11,1,15,25,0, "+09:00"))
=> 2007-11-01 15:25:00 +0900

****edited to not be completely and totally incorrect in every way****

***编辑的内容不完全,完全不正确****。

#4


6  

One command to convert date time to Unix format and then to string

一个命令将日期时间转换为Unix格式,然后转换为字符串。

    DateTime.strptime(Time.now.utc.to_i.to_s,'%s').strftime("%d %m %y")

    Time.now.utc.to_i #Converts time from Unix format
    DateTime.strptime(Time.now.utc.to_i.to_s,'%s') #Converts date and time from unix format to DateTime

finally strftime is used to format date

最后,strftime用于格式化日期。

Example:

例子:

    irb(main):034:0> DateTime.strptime("1410321600",'%s').strftime("%d %m %y")
    "10 09 14"

#5


1  

This tells you the date of the number of seconds in future from the moment you execute the code.

这将告诉您从执行代码的那一刻起,未来的秒数。

time = Time.new + 1000000000 #date in 1 billion seconds

puts(time)

把(时间)

according to the current time I am answering the question it prints 047-05-14 05:16:16 +0000 (1 billion seconds in future)

根据当前时间,我正在回答它打印的问题047-05-14 05:16:16 +0000(未来10亿秒)

or if you want to count billion seconds from a particular time, it's in format Time.mktime(year, month,date,hours,minutes)

或者如果你想从特定的时间计算出十亿秒,那就是格式时间。mktime(年、月、日、小时、分钟)

time = Time.mktime(1987,8,18,6,45) + 1000000000

puts("I would be 1 Billion seconds old on: "+time)

put(“我将有10亿秒的时间:”+time)

#6


0  

If you wanted just a Date, you can do Date.strptime(invoice.date.to_s, '%s') where invoice.date comes in the form of anFixnum and then converted to a String.

如果您想要一个日期,您可以做日期。strptime(invoice.date)。to_s ' % s '),发票。日期以anFixnum的形式出现,然后转换为字符串。

#1


277  

DateTime.strptime can handle seconds since epoch. The number must be converted to a string:

DateTime。strptime可以处理自epoch以来的秒数。数字必须转换为字符串:

require 'date'
DateTime.strptime("1318996912",'%s')

#2


551  

Sorry, brief moment of synapse failure. Here's the real answer.

抱歉,是synapse失败的短暂瞬间。这是真正的答案。

require 'date'

Time.at(seconds_since_epoch_integer).to_datetime

Brief example (this takes into account the current system timezone):

简单示例(考虑到当前系统时区):

$ date +%s
1318996912

$ irb

ruby-1.9.2-p180 :001 > require 'date'
 => true 

ruby-1.9.2-p180 :002 > Time.at(1318996912).to_datetime
 => #<DateTime: 2011-10-18T23:01:52-05:00 (13261609807/5400,-5/24,2299161)> 

Further update (for UTC):

进一步更新(UTC):

ruby-1.9.2-p180 :003 > Time.at(1318996912).utc.to_datetime
 => #<DateTime: 2011-10-19T04:01:52+00:00 (13261609807/5400,0/1,2299161)>

Recent Update: I benchmarked the top solutions in this thread while working on a HA service a week or two ago, and was surprised to find that Time.at(..) outperforms DateTime.strptime(..) (update: added more benchmarks).

最近的更新:我在一两个星期前处理HA服务的时候,在这个线程中对顶部的解决方案进行了基准测试,并且很惊讶地发现Time.at(..)超过了DateTime.strptime(..)(更新:添加了更多的基准)。

# ~ % ruby -v
#  => ruby 2.1.5p273 (2014-11-13 revision 48405) [x86_64-darwin13.0]

irb(main):038:0> Benchmark.measure do
irb(main):039:1*   ["1318996912", "1318496912"].each do |s|
irb(main):040:2*     DateTime.strptime(s, '%s')
irb(main):041:2>   end
irb(main):042:1> end

=> #<Benchmark ... @real=2.9e-05 ... @total=0.0>

irb(main):044:0> Benchmark.measure do
irb(main):045:1>   [1318996912, 1318496912].each do |i|
irb(main):046:2>     DateTime.strptime(i.to_s, '%s')
irb(main):047:2>   end
irb(main):048:1> end

=> #<Benchmark ... @real=2.0e-05 ... @total=0.0>

irb(main):050:0* Benchmark.measure do
irb(main):051:1*   ["1318996912", "1318496912"].each do |s|
irb(main):052:2*     Time.at(s.to_i).to_datetime
irb(main):053:2>   end
irb(main):054:1> end

=> #<Benchmark ... @real=1.5e-05 ... @total=0.0>

irb(main):056:0* Benchmark.measure do
irb(main):057:1*   [1318996912, 1318496912].each do |i|
irb(main):058:2*     Time.at(i).to_datetime
irb(main):059:2>   end
irb(main):060:1> end

=> #<Benchmark ... @real=2.0e-05 ... @total=0.0>

#3


38  

Time Zone Handling

时区处理

I just want to clarify, even though this has been commented so future people don't miss this very important distinction.

我只是想澄清一下,尽管这已经被评论过了,所以未来的人们不会错过这个非常重要的区别。

DateTime.strptime("1318996912",'%s') # => Wed, 19 Oct 2011 04:01:52 +0000

displays a return value in UTC and requires the seconds to be a String and outputs a UTC Time object, whereas

在UTC中显示返回值,并要求秒为字符串并输出UTC时间对象,而。

Time.at(1318996912) # => 2011-10-19 00:01:52 -0400

displays a return value in the LOCAL time zone, normally requires a FixNum argument, but the Time object itself is still in UTC even though the display is not.

在本地时区中显示一个返回值,通常需要一个FixNum参数,但是时间对象本身仍然在UTC中,即使显示不是。

So even though I passed the same integer to both methods, I seemingly two different results because of how the class' #to_s method works. However, as @Eero had to remind me twice of:

因此,即使我将相同的整数传递给了这两种方法,但由于类的#to_s方法的工作方式,我似乎得到了两个不同的结果。然而,@Eero不得不提醒我两次:

Time.at(1318996912) == DateTime.strptime("1318996912",'%s') # => true

An equality comparison between the two return values still returns true. Again, this is because the values are basically the same (although different class's, the #== method takes care of this for you), but the #to_s method prints drastically different strings. Although, if we look at the strings, we can see they are indeed the same time, just printed in different time zones.

两个返回值之间的相等比较仍然返回true。同样,这是因为这些值基本上是相同的(尽管不同的类,#==方法为您处理了这个问题),但是#to_s方法打印了截然不同的字符串。尽管,如果我们看一下字符串,我们可以看到它们确实是同时出现的,只是在不同的时区里打印出来的。

Method Argument Clarification

方法参数说明

The docs also say "If a numeric argument is given, the result is in local time." which makes sense, but was a little confusing to me because they don't give any examples of non-integer arguments in the docs. So, for some non-integer argument examples:

文档还说“如果给出了一个数字参数,结果是在本地时间。”这是有意义的,但对我来说有点困惑,因为他们没有给出文档中任何非整数参数的例子。对于一些非整数的参数例子:

Time.at("1318996912")
TypeError: can't convert String into an exact number

you can't use a String argument, but you can use a Time argument into Time.at and it will return the result in the time zone of the argument:

您不能使用字符串参数,但是可以将时间参数用于时间。它将在参数的时区返回结果:

Time.at(Time.new(2007,11,1,15,25,0, "+09:00"))
=> 2007-11-01 15:25:00 +0900

****edited to not be completely and totally incorrect in every way****

***编辑的内容不完全,完全不正确****。

#4


6  

One command to convert date time to Unix format and then to string

一个命令将日期时间转换为Unix格式,然后转换为字符串。

    DateTime.strptime(Time.now.utc.to_i.to_s,'%s').strftime("%d %m %y")

    Time.now.utc.to_i #Converts time from Unix format
    DateTime.strptime(Time.now.utc.to_i.to_s,'%s') #Converts date and time from unix format to DateTime

finally strftime is used to format date

最后,strftime用于格式化日期。

Example:

例子:

    irb(main):034:0> DateTime.strptime("1410321600",'%s').strftime("%d %m %y")
    "10 09 14"

#5


1  

This tells you the date of the number of seconds in future from the moment you execute the code.

这将告诉您从执行代码的那一刻起,未来的秒数。

time = Time.new + 1000000000 #date in 1 billion seconds

puts(time)

把(时间)

according to the current time I am answering the question it prints 047-05-14 05:16:16 +0000 (1 billion seconds in future)

根据当前时间,我正在回答它打印的问题047-05-14 05:16:16 +0000(未来10亿秒)

or if you want to count billion seconds from a particular time, it's in format Time.mktime(year, month,date,hours,minutes)

或者如果你想从特定的时间计算出十亿秒,那就是格式时间。mktime(年、月、日、小时、分钟)

time = Time.mktime(1987,8,18,6,45) + 1000000000

puts("I would be 1 Billion seconds old on: "+time)

put(“我将有10亿秒的时间:”+time)

#6


0  

If you wanted just a Date, you can do Date.strptime(invoice.date.to_s, '%s') where invoice.date comes in the form of anFixnum and then converted to a String.

如果您想要一个日期,您可以做日期。strptime(invoice.date)。to_s ' % s '),发票。日期以anFixnum的形式出现,然后转换为字符串。