datetime库
-
日期
import datetime
a = datetime.date.today() //今天的日期,年月日,datetime.date(2017, 7, 13)
datetime.datetime.combine(a, datetime.time()) //datetime.datetime(2017, 7, 13, 0, 0) -
日期和时间
b = datetime.datetime.now() //今天的时间,年月日时分秒毫秒,datetime.datetime(2017, 7, 13, 10, 47, 7, 753609)
b.date() //datetime.date(2017, 7, 13)
b.time() //datetime.time(14, 26, 23, 525904) -
计算时间间隔
c1 = datetime.timedelta(days=100) //通过时间间隔可获取前日期
c2 = datetime.timedelta(hours=24) //时间间隔可设置日、时间等间隔
a - c1 //获取a前100天日期,datetime.date(2017, 4, 4)
a + c2 //datetime.date(2017, 7, 14) -
打印时间格式
a.isformat() //标准时间格式字符串,将datetime对象转换为string,'2017-07-13'
b.strftime('%Y-%m-%d %H:%M:%S') //自定义时间格式,将datetime对象转换为string,'2017-07-13 10:47:07' -
字符串转为时间
datetime.datetime.strptime('2012-10-10', '%Y-%m-%d') //datetime.datetime(2012, 10, 10, 0, 0)
time库
-
表示日常时间
datetime.time(12, 11, 30) -
表示实际间隔,运行时长
start = time.time()
end = time.time()
time.clock() //CPU时间
time.sleep() //以秒为单位,暂停时长 -
以求1到100000的和为例进行
time.clock()
示例
import timea = input('Please input 0 or 1:') print 'Counting...' start_clock = time.clock(); if a==1: sum_i = 0 for i in range(100000): sum_i = sum_i + i else: sum_i = sum(range(100000)) print 'The result is: %d'%(sum_i) end_clock = time.clock() stop_clock = time.sleep(1) print 'Count time is: %f seconds'%(end_clock-start_clock) // 以下是运行结果 Please input 0 or 1:0 Counting... The result is: 4999950000 Count time is: 0.008170 seconds Please input 0 or 1:1 Counting... The result is: 4999950000 Count time is: 0.020432 seconds
参考资料:
网友评论