Ruby 中 DateTime 的毫秒分辨率 [英] Millisecond resolution of DateTime in Ruby

查看:28
本文介绍了Ruby 中 DateTime 的毫秒分辨率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似 2012-01-01T01:02:03.456 的字符串,我使用 ActiveRecord 将其存储在 Postgres 数据库 TIMESTAMP 中.

I have a string like 2012-01-01T01:02:03.456 that I am storing in a Postgres database TIMESTAMP using ActiveRecord.

不幸的是,Ruby 似乎截断了毫秒:

Unfortunately, Ruby seems to chop off the milliseconds:

ruby-1.9.3-rc1 :078 > '2012-12-31T01:01:01.232323+3'.to_datetime
 => Mon, 31 Dec 2012 01:01:01 +0300 

Postgrs 支持微秒分辨率.我怎样才能相应地保存我的时间戳?我需要至少毫秒的分辨率.

Postgrs supports microsecond resolution. How can I get my timestamp to be saved accordingly? I need at least millisecond resolution.

(PS 是的,我可以在 postgres 中修改一个毫秒的整数列;这样就违背了 ActiveRecord 的全部目的.)

(PS Yes I could hack in a milliseconds integer column in postgres; that kind of defeats the whole purpose of ActiveRecord.)

更新:
非常有帮助的回复表明 Ruby 的 DateTime 不是 截断毫秒;使用 #to_f 显示它.但是,做:

UPDATE:
The very helpful responses showed that Ruby's DateTime is not chopping off milliseconds; using #to_f shows it. But, doing:

m.happened_at = '2012-01-01T00:00:00.32323'.to_datetime
m.save!
m.reload
m.happened_at.to_f

确实减少了毫秒.

现在,有趣的是 created_at 确实在 Rails 和 Postgres 中显示毫秒.但是其他时间戳字段(如上面的 happened_at )没有.(也许 Rails 对 created_at 使用了 NOW() 函数,而不是传入 DateTime).

Now, the interesting thing is that created_at does show milliseconds, both in Rails and Postgres. But other timestamps fields (like happened_at above) don't. (Perhaps Rails uses a NOW() function for created_at as opposed to passing in a DateTime).

这引出了我的终极问题:
如何让 ActiveRecord 保留时间戳字段的毫秒分辨率?

Which leads to my ultimate question:
How can I get ActiveRecord to preserve millisecond resolution on timestamp fields?

推荐答案

将上面代码中的m.happened_at = '2012-01-01T00:00:00.32323'.to_datetime改为m.happened_at = '2012-01-01T00:00:00.32323' 解决了这个问题,虽然我不知道为什么.

Changing m.happened_at = '2012-01-01T00:00:00.32323'.to_datetime in the code above to m.happened_at = '2012-01-01T00:00:00.32323' solves the problem, though I have no idea why.

这篇关于Ruby 中 DateTime 的毫秒分辨率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆