time.time()Python时间模块中是否返回系统的时间或UTC时间?
我正在处理Python中的日期,我需要将它们转换为UTC时间戳,以便在Javascript中使用.以下代码不起作用:
>>> d = datetime.date(2011,01,01)
>>> datetime.datetime.utcfromtimestamp(time.mktime(d.timetuple()))
datetime.datetime(2010, 12, 31, 23, 0)
Run Code Online (Sandbox Code Playgroud)
将日期对象首先转换为datetime也无济于事.我试过这个链接的例子,但是:
from pytz import utc, timezone
from datetime import datetime
from time import mktime
input_date = datetime(year=2011, month=1, day=15)
Run Code Online (Sandbox Code Playgroud)
现在要么:
mktime(utc.localize(input_date).utctimetuple())
Run Code Online (Sandbox Code Playgroud)
要么
mktime(timezone('US/Eastern').localize(input_date).utctimetuple())
Run Code Online (Sandbox Code Playgroud)
确实有效.
所以一般的问题:如何根据UTC获得自纪元以来转换为秒的日期?
我在StackExchange上搜索了一堆解决方案,但没有什么是我需要的.在JavaScript中,我使用以下内容来计算自1970年1月1日以来的UTC时间:
function UtcNow() {
var now = new Date();
var utc = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds());
return utc;
}
Run Code Online (Sandbox Code Playgroud)
什么是等效的Python代码?
请帮我将datetime对象(例如: 2011-12-17 11:31:00-05:00)(包括时区)更改为Unix时间戳(如Python中的函数time.time()).