datetime.time():是一个时间类,这个类接受4个参数,分别代表时,分,秒,毫秒.参数的默认值是为0
1 #!/usr/bin/env python 2 #coding:utf8 3 import datetime 4 t=datetime.time(20, 00, 13, 00) 5 print t 6 print ‘*‘*20 7 print t.hour 8 print t.minute 9 print t.second 10 print t.microsecond 11 12 输出结果: 13 20:00:13 14 ******************** 15 20 16 0 17 13 18 0
datetime.date():是一个日期类,这个类接受3个参数,分别代表年,月,日
today()是这个类的方法,获取当前的日期实例
1 #!/usr/bin/env python 2 #coding:utf8 3 import datetime 4 t=datetime.date(2014,3,11) 5 print t 6 t=datetime.date.today() 7 print ‘*‘*20 8 print t 9 print t.year 10 print t.month 11 print t.day 12 13 输出结果: 14 2014-03-11 15 ******************** 16 2014-07-20 17 2014 18 7 19 20
timedeltat日期时间的算术运算
datetime.timedelta():接受7个参数,weeks,days,hours,minutes,seconds.milliseconds,microseconds,默认值为0,这个类只有一个方法total_seconds(),把传入的时间参数值转换成秒数,并返回
1 #!/usr/bin/env python 2 #coding:utf8 3 import datetime 4 #定义时间周期 5 time = datetime.timedelta(weeks=1, hours=3, seconds=88) 6 print time 7 print time.total_seconds() 8 9 输出结果 10 7 days, 3:01:28 11 615688.0
日期的算数运算
1 #!/usr/bin/env python 2 #coding:utf8 3 import datetime 4 today = datetime.date.today() 5 print today 6 test_day = datetime.timedelta(weeks=1, days=3, hours=24) 7 print today - test_day 8 9 输出结果: 10 2014-07-21 11 2014-07-10
datetime.datetime():时间类和日期类的一个组合,返回的实例包含date和time对象的几乎所有属性(不包含week和millisecond)
1 #!/usr/bin/env python 2 #coding:utf8 3 import datetime 4 now = datetime.datetime.now() 5 today = datetime.datetime.today() 6 utcnow = datetime.datetime.utcnow() 7 8 print now 9 print today 10 print utcnow 11 12 13 s = [‘year‘,‘month‘, ‘day‘, ‘hour‘, ‘minute‘, ‘second‘, ‘microsecond‘] 14 15 d = datetime.datetime.now() 16 for attr in s: 17 print ‘%15s: %s‘%(attr, getattr(d, attr)) 18 19 输出结果: 20 2014-07-21 01:31:34.434000 21 2014-07-21 01:31:34.434000 22 2014-07-20 17:31:34.434000 23 year: 2014 24 month: 7 25 day: 21 26 hour: 1 27 minute: 31 28 second: 34 29 microsecond: 434000
当然日期也可以用来比较和格式化
1 #!/usr/bin/env python 2 #coding:utf8 3 import datetime 4 t1 = datetime.time(1, 2, 3) 5 t2 = datetime.time(3, 2, 1) 6 7 print t2 < t1 8 9 输出结果: 10 False
格式化的方法
strftime():将时间转换成指定的格式,和time模块里面的用法一样
strptime():将格式化的字符串转化为datetime实例,和time模块里面的用法一样