Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Parse timestamp as though it's in a specific timezone

I'm exporting some data from Mixpanel and am trying to read in a timestamp. However, Mixpanel sends timestamps in something other than UTC.

Mixpanel Docs

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.

Example

1492100624 is a timestamp from mixpanel and it corresponds to 04/13/2017 @ 4:23pm (Central Time US). If I use Time.at to parse the timestamp it assumes the timestamp is in 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

Manually adding in 7 or 8 hours as per their docs seems prone to errors depending on if the timestamp falls before or after daylight savings. Then again, timezones are confusing, so I could be making this harder than it seems!

How should I go about correctly reading in these timestamps so I can operate on them in UTC?

Note: I'm not using rails. How can I do this in vanilla Ruby?

like image 612
Brian Wigginton Avatar asked May 19 '26 14:05

Brian Wigginton


1 Answers

This solution seems to be working for me:

t = Time.at 1492100624 // => 2017-04-13 11:23:44 -0500
t -= t.utc_offset      // => 2017-04-13 16:23:44 -0500
like image 52
Brian Wigginton Avatar answered May 22 '26 11:05

Brian Wigginton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!