【问题标题】:Handling offset naive object处理偏移天真的对象
【发布时间】:2020-01-16 13:19:42
【问题描述】:

我正在尝试根据 IST 找到直到第二天的时间。我正在使用 pytz。我不明白为什么“明天”是偏移天真的,而明天是使用偏移感知常量定义的。

我尝试打印诸如 print tomorrow_date - now 之类的东西,但结果为 0,我不知道这是怎么回事。

from datetime import datetime,timedelta
from pytz import timezone
ist = timezone('Asia/Kolkata')
def get_until_tomorrow():
    now = datetime.now(ist)
    #today = date.today()
    tomorrow_date = now + timedelta(days=1)
    tomorrow = datetime.combine(tomorrow_date,time=time(00,00))
    seconds_left = tomorrow - now
    return seconds_left.seconds
print(get_until_tomorrow())

我得到一个错误,我不能减去一个偏移量幼稚和一个偏移量感知对象。 now 是一个偏移感知对象,因为我直接设置它,但根据它,明天是一个偏移天真的变量。当我只使用偏移感知变量来定义tomorrow 时,这怎么可能?

【问题讨论】:

  • 嗨。我在下面的回答有帮助吗?

标签: python-datetime pytz


【解决方案1】:

看起来您必须通过使用本地化来使其具有偏移意识。看看这是否有帮助。

from datetime import datetime,timedelta, time
from pytz import timezone

ist = timezone('Asia/Kolkata')
def get_until_tomorrow():
    now = datetime.now(ist)
    tomorrow_date = now + timedelta(days=1)
    tomorrow = datetime.combine(tomorrow_date,time=time(00,00))
    tomorrow = ist.localize(tomorrow) 
    seconds_left = tomorrow - now
    return seconds_left.seconds
print(get_until_tomorrow())

【讨论】:

    猜你喜欢
    • 2018-02-03
    • 2010-10-22
    • 2021-07-07
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 1970-01-01
    相关资源
    最近更新 更多