当前位置: 动力学知识库 > 问答 > 编程问答 >

python - Django 1.9 date object import from csv

问题描述:

The date from my csv is in the format mm/dd/yyyy

I edited settings.py to include:

DATE_INPUT_FORMATS = [

'%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y']

# '2006-10-25', '10/25/2006', '10/25/06'

When assigning the csv row to the db model, I get this error:

TypeError: an integer is required (got type str)

This is my code:

import os

import sys

import csv

import django

from datetime import date as django_date

sys.path.append("/home/nerdbox2/django_/logbook/")

os.environ["DJANGO_SETTINGS_MODULE"] = "logbook.settings"

django.setup()

from flights.models import Flight

f = Flight()

reader = csv.reader(open('path to file'))

for row in reader: #reads row from csv

f.date = django_date(row[0])

f.aircraft = row[1]

f.save()

If I do something like: f.date = django_date(int(row[0]))

I get: ValueError: invalid literal for int() with base 10: 'date'

I think the problem is that since the input format is yyyy/mm/dd that the '/' character can't be turned into an int() but how to I make the string into a date object that Django will accept?

网友答案:

It has nothing to do with django when you want to parse an individual date string. You need to use strptime to convert datetime string into datetime objects:

import datetime
f.date = datetime.datetime.strptime('2016/01/01', '%Y/%m/%d').date()

In your case it would be:

import datetime
f.date = datetime.datetime.strptime(row[0], '%Y/%m/%d').date()
分享给朋友:
您可能感兴趣的文章:
随机阅读: