Python-time和datetime模块
一、time模块
1、表示时间的三种方式
>>> import time >>> time.time() #当前时间戳 1509525556.8485825 >>> time.localtime() #用struct_time结构保存当前时间 time.struct_time(tm_year=2017, tm_mon=11, tm_mday=1, tm_hour=16, tm_min=39, tm_s ec=24, tm_wday=2, tm_yday=305, tm_isdst=0) >>> time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) #用字符串形式格式化时间 '2017-11-01 16:39:38'
2、三种格式之间的相互转化
>>> time.gmtime(time.time()) #时间戳转化为struct_time time.struct_time(tm_year=2017, tm_mon=11, tm_mday=1, tm_hour=8, tm_min=53, tm_se c=51, tm_wday=2, tm_yday=305, tm_isdst=0) >>> time.mktime(time.localtime()) #struct_time转化为时间戳 1509526449.0 >>> time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) #struct_time转化为字符串 '2017-11-01 16:54:27' >>> time.strptime('2017-11-01', '%Y-%m-%d') #字符串转化为struct_time time.struct_time(tm_year=2017, tm_mon=11, tm_mday=1, tm_hour=0, tm_min=0, tm_sec =0, tm_wday=2, tm_yday=305, tm_isdst=-1)
3、time.sleep()表示间隔多少秒再继续
>>> while True: print('hello') time.sleep(1) #表示每隔1秒打印一次‘hello’
二、datetime模块
import datatime print(datetime.datetime.now()) #获取当前日期和时间 print(datetime.datetime.now()+datetime.timedelta(3)) #3天后的时间 print(datetime.datetime.now()+datetime.timedelta(-3)) #3天前的时间