Python vs Javascript DateTime -


i'm trying convert javascript api call python. working javascript code works fine, generating timestamp this:

var curdate = new date(); var gmtstring = curdate.togmtstring(); var utc = date.parse(gmtstring) / 1000; 

this result (this number of seconds since epoch) subsequently hashed , used in api call, relevant section. if can let me know correct way convert appreciated.

here's details on different results different methods:

javascript(valid api result)

var curdate = new date(2013, 7, 10); var gmtstring = curdate.togmtstring(); var utc = date.parse(gmtstring) / 1000; 

result: 1376089200

python (invalid api result)

from datetime import datetime import calendar  d = datetime(2013, 8, 10) calendar.timegm(d.utctimetuple()) 

result: 1376092800

i'm missing something, can enlighten me on this?

update

i had made mistake in examples, javascript uses 0 based dates , python's dates 1-based.

jonathon kindly explained difference in values different due python defaulting utc javascript defaulting local timezone. in case gmt, 1 required api. need result in python.

answer

the solution mismatch of timezones being provided. though i'm still having issues third party api, @ least getting correct times.

this can 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 datetime:

generatetimestamp(datetime(2013, 8, 10)) 

or

generatetimestamp(datetime.utcnow()) 

as side note, if you're trying out , want install pytz1 using pip, you'll can using pre tag2:

pip install --pre pytz 

for javascript dates, month argument 0 - 11. so, august, you'll want pass 7.

integer value representing month, beginning 0 january 11 december.

they have different default timezones, python defaulting utc while javascript defaults user's "local" timezone.

you can use date.utc(), returns timestamp, equivalent in javascript.

var utc = date.utc(2013, 7, 10) / 1000; // 1376092800 

side note: can use gettime() timestamp of date.

var curdate = new date(2013, 7, 10); var utc = curdate.gettime() / 1000; 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -