如何在Python中获取UTC时间? [英] How to get UTC time in Python?

查看:809
本文介绍了如何在Python中获取UTC时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在StackExchange上搜索了一堆解决方案,但是没有什么可做的。在JavaScript中,我使用以下内容来计算1970年1月1日以来的UTC时间:

I've search a bunch on StackExchange for a solution but nothing does quite what I need. In JavaScript, I'm using the following to calculate UTC time since Jan 1st 1970:

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;
}

什么是相当的Python代码?

What would be the equivalent Python code?

推荐答案

尝试使用 datetime.utcnow()

from datetime import datetime
datetime.utcnow()

为了您的目的,您需要计算在两个日期之间花费的时间,您需要的是减号结束和开始日期。这种减法的结果是 timedelta对象

For your purposes when you need to calculate an amount of time spent between two dates all that you need is to substract end and start dates. The results of such substraction is a timedelta object.

从python文档:

class datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])

意味着默认情况下,您可以获得其定义中提到的任何字段 -
天,秒,微秒,毫秒,分钟,小时,周。 timedelta实例也有total_seconds()方法:

And this means that by default you can get any of the fields mentioned in it's definition - days, seconds, microseconds, milliseconds, minutes, hours, weeks. Also timedelta instance has total_seconds() method that:


返回持续时间中包含的总秒数。
等效于(真正的分区启用)计算的(td.microseconds +(td.seconds + td.days * 24 * 3600)*
10 * 6)/ 10 * 6。

这篇关于如何在Python中获取UTC时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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