Python 在正确的时区获取当前时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/25837452/
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
Python get current time in right timezone
提问by luckydonald
Right now I use
现在我用
import datetime
print(datetime.datetime.now().strftime("%X"))
to display the current time as a string.
Problem is, my computer is running in Europe/Berlintime zone, and the offset of +2 to UTC is not accounted here.
Instead of 19:22:26it should display 21:22:26Also different to the other answers I found here, I do not store it by calling
将当前时间显示为字符串。
问题是,我的电脑在Europe/Berlin时区运行,+2 到 UTC 的偏移量这里没有计算。而不是19:22:26它应该显示21:22:26也不同于我在这里找到的其他答案,我不通过调用来存储它
datetime.datetime(2014, 7, 10, 18, 44, 59, 193982, tzinfo=<UTC>)
but
但
datetime.datetime.now()
so I tried (and failed) the following:
所以我尝试了(但失败了)以下操作:
>>> from pytz import timezone
>>> datetime.datetime.now().astimezone(timezone('Europe/Berlin'))
 ValueError: astimezone() cannot be applied to a naive datetime
Edit:
编辑:
Answer
回答
Can't post as answer, as this question is marked closed
无法发布为答案,因为此问题已标记为已关闭
The server I had this issue with doesn't exists any longer. Anyway, here are some other things worth checking:
我遇到这个问题的服务器不再存在。无论如何,这里还有一些其他值得检查的事情:
- Is the timezone of your server/system set up correctly?
- VMs or docker containers might be out of sync with the host, that's worth checking.
 
- Is the time on that computer correct? You don't ended up with +2 hours after changing the timezone?
- 您的服务器/系统的时区设置是否正确?
- 虚拟机或 docker 容器可能与主机不同步,这值得检查。
 
- 那台电脑上的时间对吗?更改时区后您没有以 +2 小时结束?
回答by jfs
To get the current time in the local timezone as a naive datetime object:
获取本地时区的当前时间作为一个简单的日期时间对象:
from datetime import datetime
naive_dt = datetime.now()
If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).
如果它没有返回预期的时间,则表示您的计算机配置错误。您应该先修复它(它与 Python 无关)。
To get the current time in UTC as a naive datetime object:
要将 UTC 中的当前时间作为一个简单的 datetime 对象:
naive_utc_dt = datetime.utcnow()
To get the current time as an aware datetime object in Python 3.3+:
要在 Python 3.3+ 中将当前时间作为感知日期时间对象获取:
from datetime import datetime, timezone
utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time
To get the current time in the given time zone from the tz database:
从 tz 数据库中获取给定时区的当前时间:
import pytz
tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)
It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.
它在 DST 转换期间工作。如果时区在过去具有不同的 UTC 偏移量,则它有效,即,即使时区对应于不同时间的多个 tzinfo 对象,它也有效。

