This question already has answers here:
RuntimeWarning: DateTimeField received a naive datetime
                                
                                    (7个答案)
                                
                        
                                26天前关闭。
            
                    
我想将csv中的DateTimeField数据存储到我的模型字段中,但是出现错误


  RuntimeWarning:DateTimeField Applications.submitted_at收到一个
  天真的日期时间(2020-01-30 11:08:20.429620)而时区支持是
  活性。运行时警告)


我的models.py

 submitted_at = models.DateTimeField(default=datetime.now, blank=True)
 form_fill_up_datetime = models.DateTimeField(auto_now=True, auto_now_add=True),


我该如何解决这个问题?

这是我的功能将csv字符串数据转换为datetimefield

def date_check(data):#
    if data is None:
        print("Date Field is empty")
        return
    try:
        try:
            date_format1 = '%m/%d/%Y %H:%M:%S'
            date_obj = datetime.datetime.strptime(data, date_format1)
            return date_obj
        except ValueError:
            print('Incorrect data format, should be YYYY-MM-DD')
            date_format2 = '%Y-%m-%d %H:%M:%S'
            date_obj = datetime.datetime.strptime(data, date_format2)
            return date_obj
    except Exception as e:
        print(e)
        return

最佳答案

您看到的不是错误,而是警告。它说您正在运行服务器时区感知,这很奇怪,然后您仍然传递没有时区的datetime对象。您可以将时区(例如UTC)添加到datetime对象:

from pytz import utc

def date_check(data):#
    if data is None:
        print("Date Field is empty")
        return
    try:
        try:
            date_format1 = '%m/%d/%Y %H:%M:%S'
            date_obj = datetime.datetime.strptime(data, date_format1)
            return utc.localize(date_obj)
        except ValueError:
            print('Incorrect data format, should be YYYY-MM-DD')
            date_format2 = '%Y-%m-%d %H:%M:%S'
            date_obj = datetime.datetime.strptime(data, date_format2)
            return utc.localize(date_obj)
    except Exception as e:
        print(e)
        return

关于python - 如何将csv datetime字符串保存到Django模型字段中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59984832/

10-12 22:41