我试图将使用python生成的UTC时间戳转换为连接客户端本地时间。但是,时间永远不会正确转换。
的Python
import time, datetime
utc_time = datetime.datetime.utcnow()
utc_time = int(time.mktime(utc_time.timetuple())) * 1000
的JavaScript
function Time(time) {
var month = {}
month[0] = "Jan";
month[1] = "Feb";
month[2] = "Mar";
month[3] = "Apr";
month[4] = "May";
month[5] = "Jun";
month[6] = "Jul";
month[7] = "Aug";
month[8] = "Sept";
month[9] = "Oct";
month[10] = "Nov";
month[11] = "Dec";
day = {}
day[0] = "Sunday";
day[1] = "Monday";
day[2] = "Tuesday";
day[3] = "Wednesday";
day[4] = "Thursday";
day[5] = "Friday";
day[6] = "Saturday";
var b = new Date();
var d = new Date(time);
var c = d.getTime() + (b.getTimezoneOffset() * 60000);
var offset = -(b.getTimezoneOffset() /60);
var res = c + (3600000 * offset);
d.setTime(res);
var days = day[d.getDay()];
var mon = d.getMonth();
var year = d.getFullYear();
var hour = d.getHours();
var minute = d.getMinutes();
var seconds = d.getSeconds();
var date = d.getDate();
return days + ' - ' + month[mon] + '/' + date + '/' + year + " - " + hour + ":" + minute + ":" + seconds;
}
console.log(Time(1429490580*1000));
// time stamp generated: Sunday - Apr/19/2015 at 4:43PM
我的数学错了还是我在python方面做错了?
答案 0 :(得分:1)
您的时间戳不正确:
import datetime
utc_time = datetime.datetime.utcnow()
timestamp = (utc_time - datetime.datetime(1970, 1, 1)).total_seconds()
答案 1 :(得分:0)
除非我误解了你的目标,否则你的Javascript看起来要复杂得多。 Unix时间戳值始终为UTC,默认情况下,基本Date.toString()将在本地客户端时区中输出。除非您需要输出格式而不是标准输出格式,否则不需要手动转换。
var ourDateTime = new Date(timestampFromServer);
console.log(ourDateTime.toString());