python学习数据类型之datetime

导入模块: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 'datetime.date'>
>>> type (b)
<type 'str'>

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 'datetime.date'>
>>> type (n)
<type 'str'>

 

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 'str'>
>>> type (b)
<type 'datetime.datetime'>

只有datetime有strptime方法,所以如果要想转换成date,time类型,可以通过datetime.date(),datetime.time()转化。

>>> c = b.date()
>>> print c
2011-10-14
>>> type (c)
<type 'datetime.date'>

 

日期比较,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 'datetime.date'>
>>> type (b)
<type 'datetime.date'> 
>>> 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

阅读更多
文章标签: python date import c n2
个人分类: PYTHON
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭