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?
Let’s compare the two results:
1401561000 – 31.05.2014 18:30:00 UTC (note that getTime() gives you number of milliseconds, so you need to divide by 1000)1398882600 – 30.04.2014 18:30:00 UTCSo 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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With