如何将 Python 日期时间对象转换为 UTC?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3327946/
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
How can I convert a Python datetime object to UTC?
提问by Elias Zamaria
I have a python datetime object which I would like to convert to UTC. I am planning to output it in RFC 2822 format to put in an HTTP header, but I am not sure if that matters for this question. I found some information on this site about converting time objects, and it looks simpler that way, but this time I really want to use datetime objects, because I am using timedeltas to adjust them:
我有一个 python datetime 对象,我想将其转换为 UTC。我打算以 RFC 2822 格式输出它以放入 HTTP 标头,但我不确定这对这个问题是否重要。我在这个站点上找到了一些关于转换时间对象的信息,这样看起来更简单,但是这次我真的想使用 datetime 对象,因为我使用 timedeltas 来调整它们:
I tried something like this:
我试过这样的事情:
from datetime import datetime, timedelta
now = datetime.now()
fiveMinutesLater = datetime.now() + timedelta(minutes=5)
fiveMinutesLaterUtc = ???
Nothing in the time or datetime module looks like it would help me. It seems like I may be able to do it by passing the datetime object through 3 or 4 functions, but I am wondering if there is a simpler way.
time 或 datetime 模块中的任何内容看起来都不会对我有帮助。似乎我可以通过将 datetime 对象传递给 3 或 4 个函数来做到这一点,但我想知道是否有更简单的方法。
I would prefer not to use third-party modules, but I may if it is the only reasonable choice.
我不想使用第三方模块,但如果这是唯一合理的选择,我可能会这样做。
采纳答案by Senyai
from datetime import datetime, timedelta
datetime.utcnow() + timedelta(minutes=5)
回答by GeekTantra
You can use the formatdate method in the email.Utils module like follows
您可以在 email.Utils 模块中使用 formatdate 方法,如下所示
>>> from email.Utils import formatdate
>>> print formatdate()
Sun, 25 Jul 2010 04:02:52 -0000
The above is date time in RFC 2822 format. By default it returns UTC time but in-case you need local time you can call formatdate(localtime=True).
以上是 RFC 2822 格式的日期时间。默认情况下,它返回 UTC 时间,但如果您需要本地时间,您可以调用 formatdate(localtime=True)。
For more information do check http://docs.python.org/library/email.mime.html#module-email.util
有关更多信息,请检查http://docs.python.org/library/email.mime.html#module-email.util
回答by Amber
First you need to make sure the datetime is a timezone-aware object by setting its tzinfomember:
首先,您需要通过设置其tzinfo成员来确保日期时间是时区感知对象:
http://docs.python.org/library/datetime.html#datetime.tzinfo
http://docs.python.org/library/datetime.html#datetime.tzinfo
You can then use the .astimezone()function to convert it:
然后,您可以使用该.astimezone()函数对其进行转换:
http://docs.python.org/library/datetime.html#datetime.datetime.astimezone
http://docs.python.org/library/datetime.html#datetime.datetime.astimezone
回答by Elias Zamaria
I found a way to take the current time, add a timedelta object to it, convert the result to UTC, and output it in RFC 2822:
我找到了一种获取当前时间的方法,向其中添加一个 timedelta 对象,将结果转换为 UTC,然后在 RFC 2822 中输出:
time.strftime("%a, %d-%b-%Y %H:%M:%S GMT",
time.gmtime(time.time() + datetime.timedelta(minutes=5).seconds))
This did not exactly answer my question, but I am putting it here because it may help someone else in my situation.
这并没有完全回答我的问题,但我把它放在这里是因为它可能对我的情况有所帮助。
EDIT:I would like to add that this trick only works if the timedelta is less than one day. If you want something that works with any sort of timedelta value, you can use timedelta.total_seconds()(for Python 2.7 and later), or with 86400*timedelta.days + timedelta.seconds. I haven't actually tried this so I'm not 100% sure if it will work.
编辑:我想补充一点,此技巧仅在 timedelta 小于一天时才有效。如果您想要使用任何类型的 timedelta 值的东西,您可以使用timedelta.total_seconds()(对于 Python 2.7 及更高版本),或使用86400*timedelta.days + timedelta.seconds. 我还没有真正尝试过这个,所以我不能 100% 确定它是否会起作用。
回答by ishmael
For those who ended up here looking for a way to convert a datetime object to UTC seconds since UNIX epoch:
对于那些最终在这里寻找一种方法来将日期时间对象转换为 UNIX 时代以来的 UTC 秒数的人:
import time
import datetime
t = datetime.datetime.now()
utc_seconds = time.mktime(t.timetuple())
回答by ElaineN
To convert to UTC from a date string:
要从日期字符串转换为 UTC:
from time import mktime
from datetime import datetime
mktime(datetime.utctimetuple(datetime.strptime("20110830_1117","%Y%m%d_%H%M")))
回答by DmitrySemenov
solutionwith fantasticDelorean lib:
具有梦幻般的Delorean lib 的解决方案:
>>> import datetime
>>> import delorean
>>> dt = datetime.datetime.now()
>>> dl = delorean.Delorean(dt, timezone='US/Pacific')
>>> dl.shift('UTC')
Delorean(datetime=2015-03-27 03:12:42.674591+00:00, timezone=UTC)
>>> dl.shift('UTC').datetime
datetime.datetime(2015, 3, 27, 3, 12, 42, 674591, tzinfo=<UTC>)
>>> dl.shift('EST').datetime
datetime.datetime(2015, 3, 26, 22, 12, 42, 674591, tzinfo=<StaticTzInfo 'EST'>)
it allows to shift datetime between different timezones easily
它允许轻松地在不同时区之间转换日期时间
回答by jfs
Here's a stdlib solution (no 3rd-party modules) that works on both Python 2 and 3.
这是一个适用于 Python 2 和 3 的 stdlib 解决方案(无第 3 方模块)。
To get the current UTC time in RFC 2822 format:
要以 RFC 2822 格式获取当前 UTC 时间:
>>> from email.utils import formatdate
>>> formatdate(usegmt=True)
'Fri, 27 Mar 2015 08:29:20 GMT'
To get the UTC time 5 minutes into the future:
要获得未来 5 分钟的 UTC 时间:
#!/usr/bin/env python
import time
from email.utils import formatdate
print(formatdate(time.time() + 300, usegmt=True)) # 5 minutes into the future
# -> Fri, 27 Mar 2015 08:34:20 GMT
回答by Carlos A. Ibarra
Use the following:
使用以下内容:
from datetime import timezone
utc_datetime = local_datetime.astimezone().astimezone(timezone.utc).replace(tzinfo=None)
Given a naive datetime object assumed to have a local datetime, you can use the following sequence of method calls to convert it to a naive UTC datetime representing the same UTC time (tested with Python 3.6.3).
假设一个初始日期时间对象具有本地日期时间,您可以使用以下方法调用序列将其转换为表示相同 UTC 时间的初始 UTC 日期时间(使用 Python 3.6.3 测试)。
- astimezone() to add the local timezone so it's no longer naive.
- astimezone(timezone.utc) to convert it from local to UTC.
- replace(tzinfo=None) to remove the timezone so it's naive again, but now UTC
- astimezone() 添加本地时区,使其不再幼稚。
- astimezone(timezone.utc) 将其从本地转换为 UTC。
- replace(tzinfo=None) 删除时区,因此它再次幼稚,但现在是 UTC
Example:
例子:
>>> local_datetime = datetime.now()
>>> local_datetime
datetime.datetime(2019, 12, 14, 10, 30, 37, 91818)
>>> local_datetime.astimezone()
datetime.datetime(2019, 12, 14, 10, 30, 37, 91818, tzinfo=datetime.timezone(datetime.timedelta(-1, 68400), 'Eastern Standard Time'))
>>> local_datetime.astimezone().astimezone(timezone.utc)
datetime.datetime(2019, 12, 14, 15, 30, 37, 91818, tzinfo=datetime.timezone.utc)
>>> local_datetime.astimezone().astimezone(timezone.utc).replace(tzinfo=None)
datetime.datetime(2019, 12, 14, 15, 30, 37, 91818)
Note: The first astimezone() is not really needed because of this note in the Python docs:
注意:第一个 astimezone() 并不是真正需要的,因为 Python 文档中的这个注释:
Changed in version 3.6: The astimezone() method can now be called on naive instances that are presumed to represent system local time.
在 3.6 版更改:现在可以在假定代表系统本地时间的朴素实例上调用 astimezone() 方法。

