Ruby - 像在特定时区中一样解析时间戳

标签 ruby timezone mixpanel

我正在从 Mixpanel 导出一些数据并尝试读取时间戳。但是,Mixpanel 以 UTC 以外的方式发送时间戳。

Mixpanel 文档

Timestamps are expressed in seconds since January 1, 1970 in your project's timezone, not UTC as a true epoch timestamp. For example, if your project is set to Pacific time, you would need to add 8 hours (or 7 hours if not in daylights savings time) (60 min * 60 secs * 8 hours) to the timestamp in order to convert this timestamp into UTC. This means that converting the raw exported timestamps using many epoch converters will result in representing times with the incorrect offset.

例子

1492100624 是来自 mixpanel 的时间戳,它对应于 04/13/2017 @ 4:23pm(美国中部时间)。如果我使用 Time.at 来解析时间戳,它会假设时间戳是 UTC。

irb(main):001:0> Time.at 1492100624
=> 2017-04-13 11:23:44 -0500
irb(main):002:0> Time.at(1492100624).utc
=> 2017-04-13 16:23:44 UTC .   # correct time in the wrong timezone

根据他们的文档手动添加 7 或 8 小时似乎容易出错,具体取决于时间戳是在夏令时之前还是之后。话又说回来,时区令人困惑,所以我可以让这比看起来更难!

我应该如何正确读取这些时间戳,以便我可以在 UTC 中对它们进行操作?

注意:我没有使用 rails。我如何在普通 Ruby 中执行此操作?

最佳答案

这个解决方案似乎对我有用:

t = Time.at 1492100624 // => 2017-04-13 11:23:44 -0500
t -= t.utc_offset      // => 2017-04-13 16:23:44 -0500

关于Ruby - 像在特定时区中一样解析时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43402488/

相关文章:

javascript - 是否可以获取 Mixpanel 存储和发送的默认值?

android - Mixpanel Analytics for Android 在离线时可以工作吗?

ruby - 在 ruby​​ hash 中使用正则表达式作为关键字

ruby - 如何使用 Ruby 替换字符串中每次出现的模式?

c++ - 时间偏移计算偏差一分钟

java - java 日历中的 future 日期出现奇怪的行为

ios - 如何使用属性跟踪混合面板时间事件?

ruby - 如何在 Ruby 中动态扩展/修改继承类的所有方法?

ruby - '在 rbuf_fill 中救援':Timeout::Error (Timeout::Error)

javascript - 无论用户的时区如何,如何始终将日期设置为东部时间