pytz 和 astimezone() 不能应用于天真的日期时间
问题描述
我有一个日期,我需要让它知道时区.
I have a date and I need to make it time zone aware.
local_tz = timezone('Asia/Tokyo')
start_date = '2012-09-27'
start_date = datetime.strptime(start_date, "%Y-%m-%d")
start_date = start_date.astimezone(local_tz)
now_utc = datetime.now(timezone('UTC'))
local_now = now_utc.astimezone(local_tz)
我需要看看这是不是真的:
I need to find if this is true:
print start_date>local_now
但我收到此错误.
start_date = start_date.astimezone(local_tz)
ValueError: astimezone() cannot be applied to a naive datetime
我将 UTC 转换为东京没有问题.我需要在东京制作 start_date 时区感知广告.
I convert utc to tokyo with no issue. I need to make start_date timezone aware ad well in tokyo.
谢谢
解决方案
对于 pytz
时区,使用他们的 .localize()
方法来转换一个幼稚的 datetime
对象与时区合二为一:
For pytz
timezones, use their .localize()
method to turn a naive datetime
object into one with a timezone:
start_date = local_tz.localize(start_date)
对于没有 DST 转换的时区,.replace()
将时区附加到天真的 datetime
对象的方法 通常也可以工作:
For timezones without a DST transition, the .replace()
method to attach a timezone to a naive datetime
object should normally also work:
start_date = start_date.replace(tzinfo=local_tz)
有关详细信息,请参阅 pytz 文档的本地化时间和日期算术.
See the localized times and date arithmetic of the pytz documentation for more details.
相关文章