Django - 'datetime.date' object has no attribute 'tzinfo'

风格不统一 提交于 2019-12-10 03:26:33

问题


Here is my code that I use to make the datetime timezone aware. I tried to use the recommended approach from the Django docs.

tradeDay = day.trade_date + timedelta(hours=6)
td1 = pytz.timezone("Europe/London").localize(tradeDay, is_dst=None)
tradeDay = td1.astimezone(pytz.utc)

I get the tz_info error. How can I datetime a tz_info attribute?

USE_TZ = True in settings.py


回答1:


It looks as though day.trade_date is actually a datetime.date object rather than a datetime.datetime so trying to localize it will cause an error.

Try converting day.trade_date to a datetime.datetime first using combine(). You can then add 6 hours and localize it.

# Convert to a datetime first
tradeDate = datetime.combine(day.trade_date, datetime.min.time())

# Now the date can be localized
tradeDay = tradeDate + timedelta(hours=6)
td1 = pytz.timezone("Europe/London").localize(tradeDay, is_dst=None)
tradeDay = td1.astimezone(pytz.utc)


来源:https://stackoverflow.com/questions/37542085/django-datetime-date-object-has-no-attribute-tzinfo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!