Python在正确的时区获取当前时间

2022-01-16 00:00:00 python time timezone

问题描述

我现在用

import datetime
print(datetime.datetime.now().strftime("%X"))

将当前时间显示为字符串.
问题是,我的电脑运行在 Europe/Berlin 时区,这里不考虑 +2 到 UTC 的偏移量.而不是 19:22:26 它应该显示 21:22:26也不同于我在这里找到的其他答案,我不通过调用来存储它

to display the current time as a string.
Problem is, my computer is running in Europe/Berlin time zone, and the offset of +2 to UTC is not accounted here. Instead of 19:22:26 it should display 21:22:26 Also different to the other answers I found here, I do not store it by calling

datetime.datetime(2014, 7, 10, 18, 44, 59, 193982, tzinfo=<UTC>)

但是

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


无法作为答案发布,因为此问题已标记为已关闭

我遇到此问题的服务器不再存在.不管怎样,这里还有一些值得检查的地方:

The server I had this issue with doesn't exists any longer. Anyway, here are some other things worth checking:

  • 您的服务器/系统的时区设置是否正确?
    • VM 或 docker 容器可能与主机不同步,这值得检查.

    解决方案

    将本地时区的当前时间作为一个简单的 datetime 对象:

    To get the current time in the local timezone as a naive datetime object:

    from datetime import datetime
    naive_dt = datetime.now()
    

    如果它没有返回预期的时间,则表示您的计算机配置错误.你应该先修复它(它与 Python 无关).

    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).

    以 UTC 格式获取当前时间作为原始日期时间对象:

    To get the current time in UTC as a naive datetime object:

    naive_utc_dt = datetime.utcnow()
    

    在 Python 3.3+ 中将当前时间作为可感知的日期时间对象获取:

    To get the current time as an aware datetime object in Python 3.3+:

    from datetime import datetime, timezone
    
    utc_dt = datetime.now(timezone.utc) # UTC time
    dt = utc_dt.astimezone() # local time
    

    从 tz 数据库中获取给定时区的当前时间:

    To get the current time in the given time zone from the tz database:

    import pytz
    
    tz = pytz.timezone('Europe/Berlin')
    berlin_now = datetime.now(tz)
    

    它在 DST 转换期间工作.如果时区在过去有不同的 UTC 偏移量,它就可以工作,即,即使时区在不同时间对应于多个 tzinfo 对象,它也可以工作.

    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.

相关文章