Python根据日期生成日志文件
使用日期时出现的问题
由于使用的日期格式为:currenttime = datetime.datetime.now()
也就是形如'%Y-%m-%d %H:%M:%S'格式的日期,在logging中,不支持这样的命名,
将以上日期改为:
thistime = time.strftime('%Y-%m-%d', time.localtime(time.time()))
也就是日期格式为'%Y-%m-%d'
亲自测试脚本代码如下
import logging
import time
thistime = time.strftime('%Y-%m-%d', time.localtime(time.time()))
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filemode='a',
filename='D:\\'+thistime+'.log'
)
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')
计算毫秒级时间差
使用python中的module:from datetime import datetime
使用该模块之后,可以使得时间的获取精确到毫秒级别
`import logging
import time
from datetime import datetime
thistime = time.strftime('%Y-%m-%d', time.localtime(time.time()))
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filemode='a',
filename='D:\Workspace\log\\'+thistime+'.log'
)
#time1 = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')
time1 = datetime.now()
#beforetime = datetime.datetime.strptime(time.localtime(time.time()), '%Y-%m-%d %H:%M:%S')
#time1 = datetime.datetime.now().microsecond
for i in range(1000):
print time1
time2 = datetime.now()
#time2 = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')
#aftertime = datetime.datetime.strptime(time.localtime(time.time()), '%Y-%m-%d %H:%M:%S')
#time2 = datetime.datetime.now().microsecond
logging.info('spend time:'+str(time2-time1))`