python将EXCEL数据导入数据库时日期型数据变成数字并加.0的问题一行代码解决方案方案

【问题描述】:python将EXCEL数据导入数据库时日期变成文本型数据并显示为数字格式
【解决方案】
数据源:
在这里插入图片描述
codes:
#!/usr/bin/python3

-- coding: utf-8 --

数据表导入数据库

import datetime
import pyodbc
import xlrd
from datetime import datetime
from xlrd import xldate_as_tuple

i = 0


def insert_data():
    global i
    try:
        db = pyodbc.connect(r'DRIVER={SQL Server Native Client 10.0};'r'SERVER=(local);'r'DATABASE=DBtest; UID=sa;PWD=726803')
    except pyodbc.InterfaceError as err:
        print(err)

    book = xlrd.open_workbook(r'C:\\Users\\Elink 001\\Desktop\\生产数据\\8号机\\table1.xls')
    sh = book.sheet_by_name('Sheet1')  # 或者sheet = workbook.sheet(n)
    cursor = db.cursor()
    rows = sh.nrows
    cols = sh.ncols
    print(rows, cols)

    for i in range(1, rows):  # 第一行是标题名,对应表中的字段名所以应该从第二行开始,计算机以0开始计数,所以值是1
        cell = sh.cell_value(i, 1)
        date = datetime(*xldate_as_tuple(cell, 0))
        time = date.strftime('%Y/%m/%d %H:%M:%S')
        
        print(time)
        # print(time1)

        sql = "insert into TEST08 (时间) values ('%s')" % (time)
        cursor.execute(sql)  # 执行sql语句
        i = i+1
        db.commit()  # 保存执行结果至数据库
    cursor.close()  # 关闭连接
    db.close()  # 关闭数据


if __name__ == '__main__':
    insert_data()

测试结果:
在这里插入图片描述
【说明】

        cell = sh.cell_value(i, 1)
        date = datetime(*xldate_as_tuple(cell, 0))
        time = date.strftime('%Y/%m/%d %H:%M:%S')
        print(time)
  • cell = sh.cell_value(i, 1)
    说明:
 def cell_value(self, rowx, colx):
    "Value of the cell in the given row and column."
    return self._cell_values[rowx][colx]
  • date = datetime(*xldate_as_tuple(cell, 0))
 #**功能:date→as_tuple,**
 def xldate_as_tuple(xldate, datemode):
    """
    Convert an Excel number (presumed to represent a date, a datetime or a time) into
    a tuple suitable for feeding to datetime or mx.DateTime constructors.

    :param xldate: The Excel number
    :param datemode: 0: 1900-based, 1: 1904-based.
    :raises xlrd.xldate.XLDateNegative:
    :raises xlrd.xldate.XLDateAmbiguous:

    :raises xlrd.xldate.XLDateTooLarge:
    :raises xlrd.xldate.XLDateBadDatemode:
    :raises xlrd.xldate.XLDateError:
    :returns: Gregorian ``(year, month, day, hour, minute, nearest_second)``.

    .. warning::

      When using this function to interpret the contents of a workbook, you
      should pass in the :attr:`~xlrd.book.Book.datemode`
      attribute of that workbook. Whether the workbook has ever been anywhere
      near a Macintosh is irrelevant.

    .. admonition:: Special case

        If ``0.0 <= xldate < 1.0``, it is assumed to represent a time;
        ``(0, 0, 0, hour, minute, second)`` will be returned.

    .. note::

        ``1904-01-01`` is not regarded as a valid date in the ``datemode==1``
        system; its "serial number" is zero.
    """
    if datemode not in (0, 1):
        raise XLDateBadDatemode(datemode)
    if xldate == 0.00:
        return (0, 0, 0, 0, 0, 0)
    if xldate < 0.00:
        raise XLDateNegative(xldate)
    xldays = int(xldate)
    frac = xldate - xldays
    seconds = int(round(frac * 86400.0))
    assert 0 <= seconds <= 86400
    if seconds == 86400:
        hour = minute = second = 0
        xldays += 1
    else:
        # second = seconds % 60; minutes = seconds // 60
        minutes, second = divmod(seconds, 60)
        # minute = minutes % 60; hour    = minutes // 60
        hour, minute = divmod(minutes, 60)
    if xldays >= _XLDAYS_TOO_LARGE[datemode]:
        raise XLDateTooLarge(xldate)
    if xldays == 0:
        return (0, 0, 0, hour, minute, second)
    if xldays < 61 and datemode == 0:
        raise XLDateAmbiguous(xldate)
    jdn = xldays + _JDN_delta[datemode]
    yreg = ((((jdn * 4 + 274277) // 146097) * 3 // 4) + jdn + 1363) * 4 + 3
    mp = ((yreg % 1461) // 4) * 535 + 333
    d = ((mp % 16384) // 535) + 1
    # mp /= 16384
    mp >>= 14
    if mp >= 10:
        return ((yreg // 1461) - 4715, mp - 9, d, hour, minute, second)
    else:
        return ((yreg // 1461) - 4716, mp + 3, d, hour, minute, second)

  • time = date.strftime(’%Y/%m/%d %H:%M:%S’)
   #  时间格式转换,保留
  def strftime(self, fmt: _Text) -> str: ...
    if sys.version_info >= (3,):
        def __format__(self, fmt: str) -> str: ...
    else:
        def __format__(self, fmt: AnyStr) -> AnyStr: ...

猜你喜欢

转载自blog.csdn.net/weixin_44322778/article/details/102891106