python向mysql写入timestamp类型的数据

在flask中连接mysql数据库的方法请参考之前写的在flask中使用mysql
使用datetime的fromtimestamp方法获得时间戳格式的时间,然后再以传参的形式写入数据库
下面写了一个注册账号的小demo, 其中inDate字段类型为timestamp,写入方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import time
from datetime import datetime

def getnowtime():
now = time.time()
nowTime = datetime.fromtimestamp(now).strftime('%Y-%m-%d %H:%M:%S')
return nowTime

def adduser(userName, passWord):
nowTime = getnowtime()
sqlStatement = "INSERT INTO `users` (`userName`, `passWord`, `roleID`, `inDate`) VALUES (%s, %s, 2, %s);"
connection = mysql.connect()
cursor = connection.cursor()
cursor.execute(sqlStatement, (userName, passWord, nowTime))
connection.commit()
return "ok"