Найти - Пользователи
Полная версия: Импорт xls с записью в MySQL - даты
Начало » Центр помощи » Импорт xls с записью в MySQL - даты
1
Trueman
Нужна помощь. Подскажите как сделать, чтобы дата из Excel файла в формате 17.02.2017 импортировалась в базу в формате 2017-02-17?

 #!/usr/bin/python3
# coding: utf-8
import xlrd
import MySQLdb
import unidecode
import datetime as dt
book = xlrd.open_workbook("excel/bid_excel.xls")
sheet = book.sheet_by_index(0)
database = MySQLdb.connect (host="localhost", user = "root", passwd = "****", db = "test")
cursor = database.cursor()
cursor.execute('SET NAMES utf8;')
cursor.execute('SET CHARACTER SET utf8;')
cursor.execute('SET character_set_connection=utf8;')
query = """INSERT INTO `bid_excel`(`one_s`, `createones_date`) VALUES (%s,%s)"""
for each in range(1, sheet.nrows):
    one_s = sheet.row(each)[0].value
    createones_date = sheet.row(each)[1].value
    values = (one_s, createones_date)
    cursor.execute(query, values)
cursor.close()
database.commit()
database.close()

При таком раскладе, в базу заносятся 0000-00-00, т.к по умолчанию NULL
4kpt_IV
|Вот тут.
Вас должно интересовать конкретно .strftime.

P.S. Внизу есть примеры…
Trueman
4kpt_IV
Спасибо за ссылку. Нашел другое решение:

 #!/usr/bin/python3
# coding: utf-8
import xlrd
import MySQLdb
import unidecode
import datetime as dt
book = xlrd.open_workbook("excel/bid_excel.xls")
sheet = book.sheet_by_index(0)
database = MySQLdb.connect (host="localhost", user = "root", passwd = "****", db = "test")
cursor = database.cursor()
cursor.execute('SET NAMES utf8;')
cursor.execute('SET CHARACTER SET utf8;')
cursor.execute('SET character_set_connection=utf8;')
query = """INSERT INTO `bid_excel`(`one_s`, `createones_date`) VALUES (%s,%s)"""
for each in range(1, sheet.nrows):
    one_s = sheet.row(each)[0].value
   purchase_date = xlrd.xldate.xldate_as_datetime(sheet.row(each)[1].value, book.datemode)
    values = (one_s, createones_date)
    cursor.execute(query, values)
cursor.close()
database.commit()
database.close()
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB