1

Am seeing strange issue when converting data time to epoch format between the languages Python and Ruby. I noticed huge difference in seconds on the same server.

In Python 3.6.2:

>>> datetime.datetime.utcnow()
datetime.datetime(2018, 1, 13, 4, 25, 19, 204056)
>>> int(datetime.datetime.utcnow().strftime("%s"))
1515839122
>>>

In Ruby 1.8.7:

irb(main):038:0> Time.now.utc
=> Sat Jan 13 04:25:18 UTC 2018
irb(main):039:0> Time.now.utc.to_i
=> 1515817520
irb(main):040:0>

Am worrying if am using wrong method in any the mentioned languages or looking way to fix this to get the same epoch seconds in both the languages. Since my application is developed to work using both the languages and the epoch time will be shared between those languages.

I believe it doesn't matter about the languages version, since the timestamp is same for irrespective of languages.

Karthi1234
  • 949
  • 1
  • 8
  • 28

1 Answers1

2

From this answer on a question about getting epoch time from Python's datetime:

Python doesn't actually support %s as an argument to strftime (if you check at http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior it's not in the list), the only reason it's working is because Python is passing the information to your system's strftime, which uses your local timezone.

That answer suggests two different methods of getting the epoch time that I had to slightly modify for UTC:

int((datetime.datetime.utcnow() - datetime.datetime(1970,1,1)).total_seconds())

and a Python 3 way:

int(datetime.datetime.now().timestamp())

The use of datetime.now() instead of datetime.utcnow() in the second solution is intentional - for reasons I'm not sure of, calling timestamp() on datetime.now() returns the UTC epoch time and on datetime.utcnow() it returns your timezone's epoch time.

user4020527
  • 1
  • 8
  • 20
  • Thanks for the clarification. calling `timestamp()` on `datetime.now()` returns the UTC epoch time is a catch. I was thinking that the `timestamp()` just returns the local timezone epoch time. It works perfect. – Karthi1234 Jan 13 '18 at 05:46