搜索UNIX时间戳会产生不同的结果

时间:2016-08-28 19:28:34

标签: ruby-on-rails ruby ruby-on-rails-4 rubygems

以下查询给出不同的结果,两者的结果应该是两个。我正在我的db(postgres)中使用timestamp列,并且正在搜索其end_at列小于或等于给定UNIX时间戳的对象。

puts object.time_records.where('time_records.end_at <= ?', object.time_records.second.end_at).count #=> 2 (Correct)
puts object.time_records.where('time_records.end_at <= ?', DateTime.strptime(object.time_records.second.end_at.to_i.to_s, '%s')).count # => 1 (Incorrect)
puts object.time_records.where('time_records.end_at <= ?', Time.at(object.time_records.second.end_at.to_i)).count # => 1 (Incorrect)

如果我为某些数据设定种子,则查询中使用的时间戳可能是:

1473024092

然后,如果我打印对象的时间戳:

puts object.time_records.pluck(:end_at).map(&:to_i)

我得到以下结果:

1472419292
1473024092
1473628892
1474233692

从这些可以看出,正确的结果应该是两个。如果有人遇到过类似的东西,我会很欣赏指向正确的方向。

对于它的价值,这是在我为宝石写的规格中发生的。我尝试了in_time_zone.utc的不同组合来解析和转换为时间戳,它们都提供相同的结果。当to_s对两者都相等时,即使转换为时间戳并直接返回到时间,并且测试相等也会导致错误。

我在irb中运行了一个例子:

2.3.0 :001 > now = Time.now
 => 2016-08-28 21:58:43 +0100 
2.3.0 :002 > timestamp = now.to_i
 => 1472417923 
2.3.0 :003 > parsed_timestamp = Time.at(timestamp)
 => 2016-08-28 21:58:43 +0100 
2.3.0 :004 > now.eql?(parsed_timestamp)
 => false 
2.3.0 :005 > now == parsed_timestamp
 => false 
2.3.0 :006 > now === parsed_timestamp
 => false 
2.3.0 :007 > now.class
 => Time 
2.3.0 :008 > parsed_timestamp.class
 => Time 

1 个答案:

答案 0 :(得分:1)

问题是分数次。 UNIX时间戳是第二个,因此在转换ggplot(data=a,aes(x=Quarter,y=Sales)) + geom_line(colour = "grey80") + geom_line(aes(colour = Season)) + geom_vline(data = ss, aes(xintercept = date), colour = "grey50") + geom_text(data = ss, aes(x = as.Date(date), y = Inf, label = Season), hjust = -0.1, vjust = 1.1) 时,毫秒被丢弃。

设置timestamp列的精度解决了这个问题:

to_i