Python学习笔记(time,logging,configparser模块)

    技术2025-01-09  17

    1.time模块

    1.1 简介:

    time模块是操作时间值的一个模块,模块里有两种时间的标准表达,第一种为时间戳,自unix诞生时(1970,1,1)开始记录秒数,第二种使用基于当地时间的9个数字的元组来表示(结构化时间),这9个数字分别表示:

    ​ year (including century, e.g. 1998) ​ month (1-12) ​ day (1-31) ​ hours (0-23) ​ minutes (0-59) ​ seconds (0-59) ​ weekday (0-6, Monday is 0) ​ Julian day (day in the year, 1-366) ​ DST (Daylight Savings Time) flag (-1, 0 or 1) ​ If the DST flag is 0, the time is given in the regular time zone; ​ if it is 1, the time is given in the DST time zone; ​ if it is -1, mktime() should guess based on the date and time.

    而我们通常用字符串时间来表示,关于字符串时间下面会讲到

    1.2 方法:

    1.2.1 time():返回时间戳

    """ time() -> floating point number Return the current time in seconds since the Epoch. time.time() """

    1.2.2 gmtime():显示标准时间UTC(本初子午线)

    ​ localtime():显示本地时间(东8区) 两种方法返回都是结构化时间

    print(time.gmtime()) # time.struct_time(tm_year=2020, tm_mon=6, tm_mday=26, tm_hour=8, tm_min=7, tm_sec=57, tm_wday=4, tm_yday=178, # tm_isdst=0) print(time.localtime()) # time.struct_time(tm_year=2020, tm_mon=6, tm_mday=26, tm_hour=16, tm_min=9, tm_sec=30, tm_wday=4, tm_yday=178, # tm_isdst=0)

    1.2.3 strftime(): 将结构化时间转换为字符串格式时间

    ''' strftime(format[, tuple]) -> string Convert a time tuple to a string according to a format specification. When the time tuple is not present, current time as returned by localtime() is used. 默认用本地时间 %Y Year with century as a decimal number. %m Month as a decimal number [01,12]. %d Day of the month as a decimal number [01,31]. %H Hour (24-hour clock) as a decimal number [00,23]. %M Minute as a decimal number [00,59]. %S Second as a decimal number [00,61]. %z Time zone offset from UTC. %a Locale's abbreviated weekday name. %A Locale's full weekday name. %b Locale's abbreviated month name. %B Locale's full month name. %c Locale's appropriate date and time representation. %I Hour (12-hour clock) as a decimal number [01,12]. %p Locale's equivalent of either AM or PM. ''' print(time.strftime('%Y-%m-%d %H:%M:%S')) # 2020-07-04 08:43:20

    1.2.4 ctime(): 把时间戳转换为本地时间的字符串

    ''' ctime(seconds) -> string Convert a time in seconds since the Epoch to a string in local time. ''' print(time.ctime(3600)) # Thu Jan 1 09:00:00 1970

    1.2.5 mktime():把本地时间的结构化时间转换为时间戳

    """ mktime(tuple) -> floating point number Convert a time tuple in local time to seconds since the Epoch. """ print(time.mktime(time.localtime())) # 1593161431.0

    1.2.6其他时间模块datetime

    import datetime print(datetime.datetime.now()) # 2020-06-26 16:58:24.869268

    2.logging模块

    2.1 简介

    python标注库提供记录日志的模块 日志分为5个级别,等级排布为critical>error>warning>info>debug,默认日志级别为warning,即在其下的级别不予执行

    2.2 配置日志格式

    # 修改配置 logging.basicConfig(level=logging.ERROR, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a %d %b %Y %H:%M:%S', filename='text.log', filemode='w') logging.debug('debug message') logging.info('info message') logging.warning('debug message') logging.error('error message') logging.critical('critical message')

    输出: Mon 05 May 2014 16:29:53 test_logging.py[line:12] ERROR error message Mon 05 May 2014 16:29:53 test_logging.py[line:13] CRITICAL critical message

    配置参数: level:设定日志等级 format:指定日志显示格式 filename:在日志以文件形式显示的时候,该文件的名字 filemode:打开文件的模式 datefmt:指定显示时间的格式 stream:使日志以屏幕形式显示(标准输出)

    format参数中可能用到的格式化串: %(levelname)s 文本形式的日志级别 %(lineno)d 调用日志输出函数的语句所在的代码行 %(message)s用户输出的消息 %(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒 %(filename)s 调用日志输出函数的模块的文件名

    2.3 logger对象

    log1=logging.getLogger() # 返回logger对象 fh = logging.FileHandler('text2.log') # filehandle控制日志发送到指定文件 sh = logging.StreamHandler() # streamhandle控制日志发送到屏幕 format=logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # 设定日志格式,返回格式对象 fh.setFormatter(format) sh.setFormatter(format) log1.addHandler(fh) log1.addHandler(sh) log1.setLevel(logging.DEBUG) log1.info('info message') # 2020-07-04 09:06:57,191 - root - INFO - info message

    可以通过Logger.setLevel(lel)指定最低的日志级别,可用的日志级别有logging.DEBUG、logging.INFO、logging.WARNING、logging.ERROR、logging.CRITICAL logger.debug()、logger.info()、logger.warning()、logger.error()、logger.critical()输出不同级别的日志,只有日志等级大于或等于设置的日志级别的日志才会被输出

    3.configparser模块

    该模块的作用 就是使用模块中的RawConfigParser()、ConfigParser()、 SafeConfigParser()这三个方法(三者择其一),创建一个对象使用对象的方法对指定的配置文件做增删改查 操作

    3.1 创建配置文件

    常用配置文件类似于字典结构,我们可以通过py字典来创建

    config=configparser.ConfigParser() config['DEFAULT']={'Dllpath':'tenio', 'lognum':'25', 'version':'20.0.2'} config['section1']={'group1':'administrator', 'group2':'hack'} config['section2']={'user':'hg', 'access':'yes'} with open('demo.ini','w') as f: config.write(f)

    3.2 增删改查

    config.read('demo.ini') # 读取配置文件 print(config.sections()) # ['section1', 'section2'] print(config['section1']['group2']) # hack for i in config: print(i) # DEFAULT,section1,section2 for i in config['DEFAULT']: print(i) config.remove_section('section1') # 删除某块 config.remove_option('section1','group1') #删除某块中某组 config.set('section2','user','www') # 修改某块某组 config.write(open('demo.ini','w')) # 修改之后重新写入

    注:DEFUALT 为配置文件默认块,在调用sections()方法时不会显示

    Processed: 0.010, SQL: 9