python function to return javascript date.getTime()

user3599803 picture user3599803 · Jul 18, 2014 · Viewed 8.5k times · Source

I'm attempting to create a simple python function which will return the same value as javascript new Date().getTime() method. As written here, javascript getTime() method returns number of milliseconds from 1/1/1970

So I simply wrote this python function:

def jsGetTime(dtime):
    diff = datetime.datetime(1970,1,1)
    return (dtime-diff).total_seconds()*1000

while the parameter dtime is a python datetime object.

yet I get wrong result. what is the problem with my calculation?

Answer

Jeff Sheffield picture Jeff Sheffield · Jul 18, 2014

One thing I feel compelled to point out here is: If you are trying to sync your client time and your server time you are going to need to pass the server time to the client and use that as an offset. Otherwise you are always going to be a bit out of sync as your clients/web-browsers will be running on various machines which have there own clock. However it is a common pattern to reference time in a unified manor using epoch milliseconds to sync between the clients and the server.

The Python

import time, datetime

def now_milliseconds():
   return int(time.time() * 1000)

# reference time.time
# Return the current time in seconds since the Epoch.
# Fractions of a second may be present if the system clock provides them.
# Note: if your system clock provides fractions of a second you can end up 
# with results like: 1405821684785.2 
# our conversion to an int prevents this

def date_time_milliseconds(date_time_obj):
   return int(time.mktime(date_time_obj.timetuple()) * 1000)

# reference: time.mktime() will
# Convert a time tuple in local time to seconds since the Epoch.

mstimeone = now_milliseconds()

mstimetwo = date_time_milliseconds(datetime.datetime.utcnow())

# value of mstimeone
# 1405821684785
# value of mstimetwo
# 1405839684000

The Javascript

d = new Date()
d.getTime()

See this post for more reference on javascript date manipulation.