返回javascript date.getTime()的python函数 [英] python function to return javascript date.getTime()

查看:136
本文介绍了返回javascript date.getTime()的python函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个简单的python函数,该函数将返回与javascript new Date().getTime()方法相同的值.按照此处所述,javascript getTime()方法返回的时间是从1970年1月1日开始的毫秒数

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

所以我只是写了这个python函数:

So I simply wrote this python function:

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

而参数dtime是python datetime对象.

while the parameter dtime is a python datetime object.

但是我得到了错误的结果.我的计算有什么问题?

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

推荐答案

在这里我不得不指出的一件事是:如果您尝试同步客户端时间和服务器时间,则需要将服务器时间传递给客户端并将其用作偏移量.否则,您的客户端/网络浏览器将在具有自己时钟的各种计算机上运行,​​因此您总是会有些不同步.但是,在统一的庄园中使用时间毫秒来在客户端和服务器之间进行同步是参考时间的常见模式.

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.

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

JavaScript

The Javascript

d = new Date()
d.getTime()

有关 javascript日期操作的更多信息,请参阅此帖子.

See this post for more reference on javascript date manipulation.

这篇关于返回javascript date.getTime()的python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆