datetime和logging模块

1.datetime模块

    datetime是python处理时间日期的标准库

类名 功能说明
date 日期对象,常用的属性有year, month, day
time 时间对象hour,minute,second,毫秒
datetime 日期时间对象,常用的属性有hour, minute, second, microsecond

timedelta

时间间隔,即两个时间点之间的长度

   时间: datetime.time( hour, minute, second, microsecond )

   日期: datetime.date( year, month, day )

   日期时间: datetime.datetime( year, month, day, hour, minute, second, microsecond )

   日期间隔:datetime.timedelta([ days, seconds, microseconds, milliseconds, minutes, hours, weeks ])  参数可选可不选,可为负

import datetime
date = datetime.date(2018,8,7)
time = datetime.time(14,47,32,24)
print(date)
print(time)

dateto = datetime.date(2020,1,14)
date = date + datetime.timedelta(days=1) #加一天后的日期
print(date)
2018-08-07
14:47:32.000024
2018-08-08

  常用函数

  • 当前日期时间: datetime.datetime.now()
  • 当前UTC(零时区)日期时间: datetime.datetime.utcnow()
  • 日期时间转时间戳:日期变量.timestamp()
  • 时间戳转日期时间: datetime.datetime.fromtimestamp(时间戳变量)
import datetime

date = datetime.datetime.now()
print(date)

datetimestamp = date.timestamp()
print(datetimestamp)

datese = datetime.datetime.fromtimestamp(datetimestamp)
print(datese)
2018-08-08 15:02:51.461179
1533711771.461179
2018-08-08 15:02:51.461179

  时间变量与字符串之间的转换

      datetime.datetime.strptime(string, format_string)    #string是字符串,format_string是时间格式   

      时间变量.strftime(format_string)   #format_string是时间格式

格式

描述

%Y / %y

年 (Y四位数表示,y两位数表示)

%m

%d

%H / %I

时(H为24时制,I为12时值,I一般和%p配合使用)

%M

%S

%p

AM / PM

import datetime

date = datetime.datetime.strptime('2018-8-8 15:09:21','%Y-%m-%d %H:%M:%S')
print(type(date))
print(date)
datestr = date.strftime('%Y-%m-%d %I:%M:%S %p')
print(type(datestr))
print(datestr)

datestr = date.strftime('%Y-%m-%d %H:%M:%S %p')
print(datestr)
<class 'datetime.datetime'>
2018-08-08 15:09:21
<class 'str'>
2018-08-08 03:09:21 PM
2018-08-08 15:09:21 PM

时区问题

    datetime.timezone(datetime.timedelta变量, name)  #datetime.timedelta变量指的是与零时区的时间间隔

                                                                                       与datetime.datetime.utcnow()相比可明显看出本时区和零时区的时间差

import datetime

time_beijing = datetime.timezone(datetime.timedelta(hours=8),'Asia/Beijing')
print(datetime.datetime(2018,7,27,15,30,20,tzinfo=time_beijing))
print(datetime.datetime.now().replace(tzinfo=time_beijing))
print(datetime.datetime.utcnow())
2018-07-27 15:30:20+08:00
2018-08-08 15:46:12.465771+08:00
2018-08-08 07:46:12.465771

2.logging模块

       日志模块,分为诊断日志和审计日志

  诊断日志

     记录与应用程序操作相关的日志,例如用户遇到的报错信息,可通过搜索诊断日志获得上下文信息

 审计日志

     为商业分析而记录的日志,从审计日志中,可提取用户的交易信息,并结合其他资料构成用户报告或者用来优化商业目标

Logging与print差异

  • print()确实方便和易用,但是也有缺点, 比如打印出来的信息不能保存,再次运行程序,之前打印出来的结果被清空
  • 日志记录包含清晰可见的诊断信息,如文件名称,路径,函数名和行号等

日志的五个级别

  • DEBUG: debug()       调试信息,通常在诊断问题的时候用得着    
  • INFO: info()               普通信息,确认程序按照预期运行    
  • WARNING: warning()             警告信息,表示发生意想不到的事情,或者指示接下来可能会出现一些问题,     但是程序还是继续运行    
  • ERROR: error()             错误信息,程序运行中出现了一些问题,一些功能没有执行    
  • CRITICAL: critical()       危险信息,一个严重的错误,导致程序无法继续运行

   级别依次升高,默认会显示warning及以上级别的日志,可通过debug.basicConfig(level=logging.级别)更改

import logging

logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.critical('critical')
WARNING:root:warning
ERROR:root:error
CRITICAL:root:critical

 设置最低显示级别

import logging

logging.basicConfig(level=logging.INFO) #级别小于level不显示

logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.critical('critical')
INFO:root:info
WARNING:root:warning
ERROR:root:error
CRITICAL:root:critical

logging的用法

     1.创建一个logging对象,设置级别

     2.定义Handler,决定把日志发送到那里

        常用的是StreamHandler和FileHandler

        StreamHandler:将日志在控制台输出    FileHandler:   将日志记录到文件里面

    3.定义handler输入信息的格式

       例如:'[%(asctime)s] [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S'

    4.将handler添加至loger对象中

    Formatter已有的数据格式(用于捕捉错误信息)

  •  %(name)s Logger的名字
  • %(levelname)s 文本形式的日志级别
  • %(message)s 用户输出的消息
  • %(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
  • %(levelno)s 数字形式的日志级别
  • %(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
  • %(filename)s 调用日志输出函数的模块的文件名
  • %(module)s  调用日志输出函数的模块名
  • %(funcName)s 调用日志输出函数的函数名
  • %(lineno)d 调用日志输出函数的语句所在的代码行
  • %(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
  • %(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数 %(thread)d 线程ID。可能没有 %(threadName)s 线程名。可能没有
  • %(process)d 进程ID。可能没有

小案例(打开文件出错写进日志)

import logging
#1.创建logger
#运行python文件首先检索__main__,此时__name__即为文件名
logger = logging.getLogger('%s_log'%__name__)  

#2.创建一个handler,用于将日志写入文件,并指定日志等级
file = logging.FileHandler('test.log', mode='a')
file.setLevel(logging.ERROR)  

#3.定义handler输出格式(参见上表和输出) 
Format = logging.Formatter("%(asctime)s-%(filename)s [line:%(lineno)d]-%(levelname)s:%(message)s")
file.setFormatter(Format)  

#4.将handler添加至logging对象中
logger.addHandler(file)

try: 
    with open('test.log') as f:  #默认只能读,所以会报错
        f.write("print('down')")
except Exception as res:
     logger.error(res)   #因设置等级为error,若此时logger.info(res)则不会写入日志

test.log便会记录一条日志

2018-08-08 16:49:03,810-test3.py [line:14]-ERROR:not writable

猜你喜欢

转载自blog.csdn.net/weixin_42089175/article/details/81484868
今日推荐