python – 如何解决strptime()引起的天真日期时间RuntimeWarning?

我正在尝试编码而不会在我的控制台中发出任何警告.到目前为止,我一直非常擅长避免它,直到这一个案例,这对我来说似乎是一个鸡和鸡蛋的情况.

from datetime import datetime as dt 

last_contacted = "19/01/2013"
current_tz = timezone.get_current_timezone()
date_time = dt.strptime(last_contacted,get_current_date_input_format(request))
date_time = current_tz.localize(date_time)

第三行是抛出这个警告:

RuntimeWarning: DateTimeField received a naive datetime (2013-01-19
00:00:00) while time zone support is active.)

它有点奇怪,因为我需要先将unicode转换为日期时间才能在第四行将datetime对象转换为datetime-aware对象(带有timezone支持).

专家的任何建议?

谢谢

更新:

def get_current_date_input_format(request):
    if request.LANGUAGE_CODE == 'en-gb':
        return formats_en_GB.DATE_INPUT_FORMATS[0]
    elif request.LANGUAGE_CODE == 'en':        
        return formats_en.DATE_INPUT_FORMATS[0]

解决方法

评论到你的问题,我猜你在你的代码中真正拥有的是这样的:

from datetime import datetime as dt 

last_contacted = "19/01/2013"
current_tz = timezone.get_current_timezone()
model_instance.date_time = dt.strptime(last_contacted,get_current_date_input_format(request))
model_instance.date_time = current_tz.localize(date_time)

其中model_instance是Model的一个实例,它具有一个名为date_time的DateTimeField.

class MyModel(models.Model)
    ....
    date_time = DateTimeField()

Python datetime.strptime函数返回一个天真的日期时间对象,您尝试将其分配给DateTimeField,然后生成警告,因为启用时区支持时,非天真日期时间对象的使用不正确.

如果将对strptime和localize的调用组合在一行上,则在分配到date_time之前完成从天真日期时间到非天真日期时间的转换的完整计算,因此在这种情况下您不会收到错误.

附加说明:如果请求中没有时区,则get_current_date_input_format函数应返回一些认时区,否则strptime调用将失败.

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...