pytz和astimezone()不能应用于天真的日期时间 [英] pytz and astimezone() cannot be applied to a naive datetime

查看:477
本文介绍了pytz和astimezone()不能应用于天真的日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  local_tz =时区('亚洲/东京' )
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)

我需要找到是否真的:

  print start_date> ; local_now 

但是我收到这个错误。

  start_date = start_date.astimezone(local_tz)
ValueError:astimezone()不能应用于天真的datetime

我没有问题,将utc转换为东京。我需要在东京建立start_date时区感知广告。



谢谢

解决方案

对于 pytz timezones,请使用他们的 .localize()方法来转换一个天真的日期时间对象变成一个带有时区的对象:

  start_date = local_tz.localize(start_date)

对于没有DST转换的时区, .replace()方法将时区附加到天真的 datetime 对象通常也可以正常工作:

  start_date = start_date.replace(tzinfo = local_tz)

请参阅本地化时间和日期算术的更多详细信息。


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

But I get this error.

   start_date = start_date.astimezone(local_tz)
   ValueError: astimezone() cannot be applied to a naive datetime

I convert utc to tokyo with no issue. I need to make start_date timezone aware ad well in tokyo.

Thanks

解决方案

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)

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)

See the localized times and date arithmetic of the pytz documentation for more details.

这篇关于pytz和astimezone()不能应用于天真的日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆