日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

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

發布時間:2025/3/20 python 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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_tuplei = 0def insert_data():global itry: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.nrowscols = sh.ncolsprint(rows, cols)for i in range(1, rows): # 第一行是標題名,對應表中的字段名所以應該從第二行開始,計算機以0開始計數,所以值是1cell = 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+1db.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) intoa 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, youshould pass in the :attr:`~xlrd.book.Book.datemode`attribute of that workbook. Whether the workbook has ever been anywherenear a Macintosh is irrelevant... admonition:: Special caseIf ``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 - xldaysseconds = int(round(frac * 86400.0))assert 0 <= seconds <= 86400if seconds == 86400:hour = minute = second = 0xldays += 1else:# second = seconds % 60; minutes = seconds // 60minutes, second = divmod(seconds, 60)# minute = minutes % 60; hour = minutes // 60hour, 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 + 3mp = ((yreg % 1461) // 4) * 535 + 333d = ((mp % 16384) // 535) + 1# mp /= 16384mp >>= 14if 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: ...

總結

以上是生活随笔為你收集整理的python将EXCEL数据导入数据库时日期型数据变成数字并加.0的问题一行代码解决方案方案的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。