Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python to JavaScript unix time conversion

In JavaScript:

new Date(2014, 5, 1).getTime()
// results: 1401561000000

While in python:

import time
import datetime
time.mktime(datetime.datetime(2014, 5 , 1).timetuple())
# results -> 1398882600.0

How can I convert python time to a JavaScript unix time stamp?

like image 552
sudhanshu Avatar asked Apr 25 '26 23:04

sudhanshu


2 Answers

Let’s compare the two results:

  1. JavaScript: 1401561000 – 31.05.2014 18:30:00 UTC (note that getTime() gives you number of milliseconds, so you need to divide by 1000)
  2. Python: 1398882600 – 30.04.2014 18:30:00 UTC

So there are actually two issues:

First of all, in JavaScript, the month index is starting at 0 (0 = January) while in Python it starts as 1 (1 = January). So that’s where the one-month offset comes from.

The second issue is due to timezones. Your local time seems to be UTC-05:30, which is where that offset comes from. When you create a date in either language, you are always using local time, so your timezone offset gets taken into account. If you want to enter UTC dates, you can also do this. In JavaScript, it’s simple thanks to Date.UTC:

Date.UTC(2014, 5, 1) / 1000 // 1401580800
Date.UTC(2014, 4, 1) / 1000 // 1398902400

In Python however, it is a bit more complicated as datetime objects are by default timezone-unaware but time.mktime assumes local time for the passed tuple. To solve this, you can either make the datetime object aware by specifying the timezone explicitely, or by performing the calculation yourself:

>>> datetime.datetime(2014, 6, 1, tzinfo=timezone.utc).timestamp()
1401580800.0
>>> datetime.datetime(2014, 5, 1, tzinfo=timezone.utc).timestamp()
1398902400.0

>>> (datetime.datetime(2014, 6, 1) - datetime.datetime(1970, 1, 1)) / datetime.timedelta(seconds=1)
1401580800.0
>>> (datetime.datetime(2014, 5, 1) - datetime.datetime(1970, 1, 1)) / datetime.timedelta(seconds=1)
1398902400.0
like image 154
poke Avatar answered Apr 28 '26 12:04

poke


JavaScript's Epoch Time starts it's month index at 0. Thus you are inputting the wrong month if you wish to get April in your JavaScript.

To fix your JavaScript to make it the same as your Python:

var time = new Date(2014, 4, 1).getTime()/1000;
// time = 1398916800
like image 38
Sleep Deprived Bulbasaur Avatar answered Apr 28 '26 12:04

Sleep Deprived Bulbasaur