时间模块平时用到的很少,你可以简单阅读。
一、time模块:
1.time.time()函数:
>>> import time
>>> time.time()
1503382778.8300416
2.
time.sleep()函数:让程序执行暂停一段时间,比如用来倒计时。
import time
timeLeft = 60
while timeLeft > 0:
print(timeLeft)
time.sleep(1)
timeLeft = timeLeft - 1
顺便说一下数字的四舍五入:
>>> round(now, 4)
1503383467.8034
>>> round(now)
1503383468
>>> round(now, 2)
1503383467.8
>>> now
1503383467.8033624
>>> now = time.time()
>>> now
1503383599.695642
>>> round(now, 2) #四舍五入后为.70,所以输出看到只有一位,其实是隐藏了0
1503383599.7
>>> now = time.time()
>>> now
1503383641.0323138
>>> round(now, 2)
1503383641.03 #和这里对比
二、datetime模块:
1.datetime.datetime.now()方法:获得当前时间。
>>> import datetime
>>> dt = datetime.datetime.now()
>>> dt
datetime.datetime(2017, 8, 22, 14, 58, 1, 632165)
>>> dt.year
2017
>>> dt = datetime.datetime.now()
>>> dt
datetime.datetime(2017, 8, 22, 15, 12, 26, 207014)
>>> datetime.datetime.fromtimestamp(1000000) #Unix纪元后1000000秒的时刻
datetime.datetime(1970, 1, 12, 21, 46, 40)
>>> datetime.datetime.fromtimestamp(time.time()) datetime.datetime(2017, 8, 22, 15, 14, 4, 630473)
datetime对象可以用比较操作符进行比较:
>>> dt1 = datetime.datetime.fromtimestamp(1000000)
>>> dt2 = datetime.datetime.fromtimestamp(time.time())
>>> dt2 - dt1
datetime.timedelta(17388, 70171, 849749)
>>> dt2 > dt1
True
2.timedelta数据类型:表示一段时间,而不是一个时刻。其中,关键字参数可以为weeks、days、hours、minutes、seconds、milliseconds和microseconds。
>>> import datetime
>>> dt = datetime.timedelta(days = 1, hours = 3, minutes = 5, seconds = 7)
>>> dt.days, dt.seconds, dt.microseconds #天、秒、微秒
(1, 11107, 0) #11107指3小时5分7秒
>>> dt.total_seconds() #以秒表示的时间
97507.0 #1天3小时5分钟7秒一共为97507.0秒
>>> str(dt)
'1 day, 3:05:07'
实例:计算今天之后100天的日期:
>>> import datetime
>>> dt = datetime.datetime.now()
>>> dt
datetime.datetime(2017, 8, 22, 15, 53, 3, 589050)
>>> nextTime = datetime.timedelta(days = 100)
>>> dt + nextTime
datetime.datetime(2017, 11, 30, 15, 53, 3, 589050)
也可以将这个时间延迟与time.sleep()混用,让程序暂停直到某一时刻:
import datetime, time
dt = datetime.datetime(2017, 8 ,23)
while datetime.datetime.now() < dt:
time.sleep(1)
3.将datetime对象转换为字符串:strftime()方法能将datetime对象显示为字符串,strftime()函数名中的f表示格式,即format。
>>> import datetime
>>> dt = datetime.datetime(2017, 8, 22, 17, 30)
>>> dt.strftime('%Y/%m/%d %H:%M:%S')
'2017/08/22 17:30:00'
>>> dt.strftime('%I:%M %p')
'05:30 PM'
将字符串转换成datetime对象:
>>> datetime.datetime.strptime('2017/8/22 17:30:00', '%Y/%m/%d %H:%M:%S')
datetime.datetime(2017, 8, 22, 17, 30)