pytz and astimezone() cannot be applied to a naive datetime(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.
这篇关于pytz 和 astimezone() 不能应用于天真的日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:pytz 和 astimezone() 不能应用于天真的日期时间
- 计算测试数量的Python单元测试 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
