导入模块:import datetime
class:
datetime.datetime
datetime.date
datetime.time
datetime.timedelta
datetime.tzinfo
>>> a = datetime.datetime.today()
>>> print a
2011-10-14 11:31:27.173391
>>> a = datetime.date.today()
>>> print a
2011-10-14
日期与字符转化:
>>> a = datetime.date.today()
>>> print a
2011-10-14
>>> b = str(a)
>>> print b
2011-10-14
>>> type (a)
>>> type (b)
datetime,date,time都可以通过str(...)转化成字符类型。但是不能确定格式?
转化成固定格式的字符,strftime(format):
>>> m = datetime.date.today()
>>> print m
2011-10-14
>>> n = m.strftime('%Y-%m-%d')
>>> print n
2011-10-14
>>> type (m)
>>> type (n)
date,datetime,time都有strftime方法。
字符转化成日期,strptime(str,format):
>>> a = '2011-10-14'
>>> b = datetime.datetime.strptime(a,'%Y-%m-%d')
>>> print a
2011-10-14
>>> print b
2011-10-14 00:00:00
>>> type (a)
>>> type (b)
只有datetime有strptime方法,所以如果要想转换成date,time类型,可以通过datetime.date(),datetime.time()转化。
>>> c = b.date()
>>> print c
2011-10-14
>>> type (c)
日期比较,python日期可以直接用'>','<','>='等直接比较,但数据类型必须要一致:
>>> a = "2011-10-14"
>>> b = "2011-10-14"
>>> a = datetime.datetime.strptime('2011-10-14','%Y-%m-%d').date()
>>> b = datetime.datetime.strptime('2011-10-15','%Y-%m-%d').date()
>>> print a,b
2011-10-14 2011-10-15
>>> type (a)
>>> type (b)
>>> if (a < b):
print "NO"
NO
>>>
日期差,datetime.timedelta:
>>> a = datetime.date(year=2011,month=10,day=15)
>>> c = a - datetime.timedelta(days=3)
>>> print c
2011-10-12