I'm trying to convert a Javascript API call to Python. The working javascript code works fine, generating a timestamp like this:
var curdate = new Date();
var gmtstring = curdate.toGMTString();
var utc = Date.parse(gmtstring) / 1000;
This result (this number of seconds since the epoch) is subsequently hashed and used in the API call, but this is the relevant section. If anyone can let me know the correct way to convert this it would be much appreciated.
Here's some details on the different results from the different methods:
var curdate = new Date(2013, 7, 10);
var gmtstring = curdate.toGMTString();
var utc = Date.parse(gmtstring) / 1000;
Result: 1376089200
from datetime import datetime
import calendar
d = datetime(2013, 8, 10)
calendar.timegm(d.utctimetuple())
Result: 1376092800
I'm clearly missing something, can anyone enlighten me on this?
I had originally made a mistake in my examples, as Javascript uses 0 based dates and Python's dates are 1-based.
Jonathon kindly explained the difference in the values is different due to a Python defaulting to UTC where as Javascript is defaulting to the local timezone. In my case this is GMT, which is the one required by the API. I now just need to get this result in Python.
The solution was a mismatch of the timezones being provided. Though I'm still having issues with the third party api, I am at least now getting the correct times.
This can probably be cleaned up:
from datetime import datetime
import calendar
import time
import pytz
def GenerateTimeStamp(d):
europe = pytz.timezone('Europe/London')
d = europe.localize(d)
tuple = d.utctimetuple()
timestamp = int(time.mktime(tuple))
return timestamp
Just provide a datetime:
GenerateTimeStamp(datetime(2013, 8, 10))
or
GenerateTimeStamp(datetime.utcnow())
As a side note, if you're trying this out and want to install pytz1 using pip, you'll can get it using the pre tag2:
pip install --pre pytz
For JavaScript Dates, the month
argument is 0 - 11. So, for August, you'll want to pass 7
.
Integer value representing the month, beginning with 0 for January to 11 for December.
They also have different default timezones, with Python defaulting to UTC while JavaScript defaults to the user's "local" timezone.
You can use Date.UTC()
, which returns the timestamp, for the equivalent in JavaScript.
var utc = Date.UTC(2013, 7, 10) / 1000;
// 1376092800
Side note: You can use getTime()
to get the timestamp of a Date
.
var curdate = new Date(2013, 7, 10);
var utc = curdate.getTime() / 1000;
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