python date,datetime 和time的区别

Python032

python date,datetime 和time的区别,第1张

datetime和time是Python中的两个内置包,但是没有date包。

time包提供的接口与C标准库time.h基本一致。相比于time模块,datetime模块的接口则更直观、更容易调用。

time包可以直接获取Unix时间戳,

import time

print time.time()

# 1437653274.549

而datetime可以直接获取表示当前日期的对象,

from datetime import datetime

print datetime.now()

# 2015-07-23 20:10:14.087000

先连接数据库,设置sql语句变量,然后游标打开变量,最后关闭游标,代码如下

conn=MySQLdb.connect(host="localhost",user="root",passwd="twet",db="test",charset="utf8")

cursor = conn.cursor()

sql = "insert into table(date) values(2014年4月1日)"

cursor.execute(sql)

cursor.close()

datetime 模块为日期和时间处理同时提供了简单和复杂的方法。支持日期和时间算法的同时,实现的重点放在更有效的处理和格式化输出。该模块还支持时区处理。

>>> # dates are easily constructed and formatted

>>> from datetime import date

>>> now = date.today()

>>> now

datetime.date(2003, 12, 2)

>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")

'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'

>>> # dates support calendar arithmetic

>>> birthday = date(1964, 7, 31)

>>> age = now - birthday

>>> age.days

14368