首页 > 代码库 > 时间模块和日志模块

时间模块和日志模块

 

import time

print(time.time()) 打印时间戳 从unix发行时间
print(time.ctime()) 打印当前时间
print(time.ctime(time.time()-86400)) 打印当前时间减去一天

time_obj = time.gmtime()
print(time_obj.tm_year,time_obj.tm_mon) 指定打印 只打印年月

print("{a}-{b}".format(a=time_obj.tm_year,b=time_obj.tm_mon)) 格式换 打印
print(time.localtime()) 打印当前时间

把时间转换为时间戳
print(time.mktime(time_obj))
tm2= time.strptime("2016-12-13","%Y-%m-%d")
print(time.mktime(tm2))

time.sleep(3) 暂停三秒
print("111111111")

指定格式打印
tm = time.strftime("%Y%m%d %H:%M:%S",time.gmtime())
tm1 = time.strftime("%Y%m%d %H:%M:%S",time.localtime())
tm2= time.strptime("2016-12-13","%Y-%m-%d")
print(time.mktime(tm2))

 

import datetime

print(datetime.date.today()) 打印结果2016-12-13
print(datetime.date.fromtimestamp(time.time()))

打印当前时间
current_time = datetime.datetime.now()
print(current_time)
print(current_time.timetuple())

print(datetime.datetime.now() + datetime.timedelta(days=-1)) 打印当前时间 减去一天 或者加一天
print(datetime.datetime.now() + datetime.timedelta(hours=10)) 减去一小时

指定日期打印
a= datetime.datetime.now()
print(a.replace(2016,12,10))

指定格式打印
print(datetime.datetime.strptime("2016-12-13 19:23","%Y-%m-%d %H:%M"))

判断大小
current_time = datetime.datetime.now()
t = current_time.replace(2015,5)
print(current_time>t)

 

import logging

简单打印

logging.basicConfig(filename=‘example.log‘,level=logging.INFO, 定义文件和INFO级别
format=‘%(asctime)s %(message)s‘,datefmt=‘%Y-%m-%d %I:%S %p‘) 打印日期
logging.debug(‘This message shouid go to then log file‘)
logging.info(‘S should this‘)
logging.warning(‘And this too‘)

 

复杂
import logging

logger = logging.getLogger(‘TEST-LOG‘) 定义模块名或者用户名
logger.setLevel(logging.INFO) 设置局部级别

ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG) 设置全局级别

fh = logging.FileHandler("access.log") 追加文件名
fh.setLevel(logging.WARNING) 级别
fh_err = logging.FileHandler("error.log") 文件
fh_err.setLevel(logging.ERROR) 级别


formatter = logging.Formatter(‘%(asctime)s - %(filename)s - %(levelname)s - %(message)s‘) 时间格式
formatter_for_file = logging.Formatter(‘%(asctime)s - %(levelname)s - %(message)s‘) 时间格式

ch.setFormatter(formatter) 指定格式
fh.setFormatter(formatter_for_file) 指定格式
fh_err.setFormatter(formatter) 指定格式

logger.addHandler(ch) 注册
logger.addHandler(fh) 注册
logger.addHandler(fh_err) 注册

设置打印内容
logger.debug(‘debug message‘)
logger.info(‘info message‘)
logger.warn(‘warn message‘)
logger.error(‘error message‘)
logger.critical(‘critical message‘)

 

 

 

 






 

时间模块和日志模块