如何在 Python 中获取 UTC 时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15940280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:25:09  来源:igfitidea点击:

How to get UTC time in Python?

pythondatetime

提问by James Clarke

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:

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

What would be the equivalent Python code?

什么是等效的 Python 代码?

回答by Artsiom Rudzenka

Try this code that uses datetime.utcnow():

试试这个使用datetime.utcnow() 的代码:

from datetime import datetime
datetime.utcnow()

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.

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

From the python docs:

从 python 文档:

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

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:

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

Return the total number of seconds contained in the duration. Equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10*6) / 10*6 computed with true division enabled.

返回持续时间中包含的总秒数。相当于 (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10* 6) / 10*6 在启用真正除法的情况下计算。

回答by Mark Ransom

In the form closest to your original:

以最接近原件的形式:

import datetime

def UtcNow():
    now = datetime.datetime.utcnow()
    return now

If you need to know the number of seconds from 1970-01-01 rather than a native Python datetime, use this instead:

如果您需要知道 1970-01-01 的秒数而不是本机 Python datetime,请改用:

return (now - datetime.datetime(1970, 1, 1)).total_seconds()

Python has naming conventions that are at odds with what you might be used to in Javascript, see PEP 8. Also, a function that simply returns the result of another function is rather silly; if it's just a matter of making it more accessible, you can create another name for a function by simply assigning it. The first example above could be replaced with:

Python 的命名约定与您在 Javascript 中可能习惯的命名约定不一致,请参阅PEP 8。此外,一个简单地返回另一个函数的结果的函数是相当愚蠢的;如果只是为了使其更易于访问,您可以通过简单地分配函数来为函数创建另一个名称。上面的第一个示例可以替换为:

utc_now = datetime.datetime.utcnow

回答by hectorcanto

From datetime.datetime you already can export to timestamps with method strftime. Following your function example:

从 datetime.datetime 您已经可以使用方法 strftime 导出到时间戳。按照您的功能示例:

import datetime
def UtcNow():
    now = datetime.datetime.utcnow()
    return int(now.strftime("%s"))

If you want microseconds, you need to change the export string and cast to float like: return float(now.strftime("%s.%f"))

如果您想要微秒,则需要更改导出字符串并将其转换为浮动,例如: return float(now.strftime("%s.%f"))

回答by MikeL

import datetime
import pytz

# datetime object with timezone awareness:
datetime.datetime.now(tz=pytz.utc)

# seconds from epoch:
datetime.datetime.now(tz=pytz.utc).timestamp() 

# ms from epoch:
int(datetime.datetime.now(tz=pytz.utc).timestamp() * 1000) 

回答by Cesar Canassa

Timezone aware with zero external dependencies:

时区感知零外部依赖:

from datetime import datetime, timezone

def utc_now():
    return datetime.utcnow().replace(tzinfo=timezone.utc)

回答by STREET MONEY

In Python 3 using lambda expression, try out;

在 Python 3 中使用 lambda 表达式,试试看;

from datetime import datetime
utc_now = lambda : datetime.utcnow()

and call the function normally;

并正常调用函数;

print(utc_now())

回答by Tim Richardson

Simple, standard library only, for modern python. Gives timezone-aware datetime, unlike datetime.utcnow(). datetimeswithout timezones are accidents waiting to happen.

仅用于现代 Python 的简单标准库。与datetime.utcnow(). datetimes没有时区是等待发生的事故。

from datetime import datetime,timezone
now_utc = datetime.now(timezone.utc)