2016-04-05 24 views
0

我有一個數據庫應該被移動到一個新的。我的想法是一個Python腳本,它讀取所有舊條目,將它們轉換爲新格式並將它們發送到新數據庫。 問題是日期(時間)以不同的方式存儲。在舊的數據庫中有5列(年,月,日,小時,分鐘),但新的只與日期時間字段(YYYY-MM-DD hh:mm:ss)一起工作。爲mysql日期時間字段創建並插入一個strftime對象

如果我嘗試在Python是這樣的:

import time 
t = time.mktime((2015,11,29,14,30,0,0*,246*,-1*))  # * not sure about these values 
print time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(t)) 

我甚至得到比預期的另一時間:

2015-11-29 13:30:00 

我如何獲得18萬項權日期時間格式,或者這是可能已經將錯誤的方法輸入到日期時間字段中了?

編輯:

import MySQLdb 

mysql_opts = { 
'host': "123.45.67.89", 
'user': "user", 
'pass': "password", 
'db': "db"} 

t = time.mktime((2015, 11, 29, 14, 30, 0, 0, 0, 0)) 
date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(t)) 
data = [date,...] 

mysql = MySQLdb.connect(mysql_opts['host'],mysql_opts['user'],mysql_opts['pass'],mysql_opts['db']) 
cursor = mysql.cursor() 

cursor.execute("INSERT INTO table (date, ...) VALUES(%s,...)",(data[0],...)) 

mysql.commit() 
mysql.close() 

如果我試試這個我收到此錯誤:

TypeError: not all arguments converted during string formatting 

還有什麼我必須做之前,我可以添加一個條目? :S

+0

爲您的其他問題,似乎你沒有相同數量的% s作爲數據的數量 –

回答

0

好像你正在做的是正確的,但不打印在GMT時間:

# get from old DB 
Y = 2015 
m = 11 
d = 29 
H = 14 
M = 30 
S = 0 

t = time.mktime((Y, m, d, H, M, S, 0, 0, 0)) 
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(t)) # use this to get the same time 

Out[1]: '2015-11-29 14:30:00' 
+0

謝謝,比我想象的要容易得多。也許你可以幫助我處理另一個問題(請參閱上面編輯的帖子)? – Ragyal

相關問題