datetime、logging

python常用模块

一、datetime模块

1.概述

datetime是python处理时间和日期的标准库,它由以下几个模块组成:

类名功能说明
date日期对象,year,month,day
time时间对象,hour,minute,second,microsecond
datetime时间日期对像
timedelta时间间隔,两个时间点之间的长度

2.时间表示知识普及

  1. 时区

  2. 格林威治时间,UTC,国际标准时间

    就是零时区的时间,英国。

  3. 时间戳(timestamp)

    是指某个时间距离格林威治时间1970,1,1,00:00:00 的总秒数。

3.模块接口

(1).常用方法
from datetime import datetime
# 获取当前日期时间
d = datetime.now()
print(d, type(d))
print(d.year, d.month, d.day, d.hour, d.minute, d.second, type(d.year))
print("-" * 50)

# 日期时间——》时间戳
ts = d.timestamp()
print(ts, type(ts))
print("-" * 50)

# 时间戳——》日期时间
ds = datetime.fromtimestamp(ts)
print(ds, type(ds))
print("-" * 50)

# 时间日期对象——》字符串
d_str = d.strftime("%Y-%m-%d    %H:%M:%S")
print(d_str, type(d_str))
print("-" * 50)

# 字符串——》日期时间对象
d = datetime.strptime(d_str, '%Y-%m-%d %H:%M:%S') #''内的格式与d-str一致
print(d, type(d))
print("-" * 50)

# 直接创建一个datetime对象
new_d = datetime(year=2019, month=5, day=23)
print(new_d, type(new_d))
d_str = "2019-5-23"
one, two, three = d_str.split("-")
print(one, type(one))
new_d = datetime(year=int(one), month=int(two), day=int(three))
print(new_d, type(new_d))

************************************************************************
2019-05-23 10:35:44.721203 <class 'datetime.datetime'>
2019 5 23 10 35 44 <class 'int'>
--------------------------------------------------
1558578944.721203 <class 'float'>
--------------------------------------------------
2019-05-23 10:35:44.721203 <class 'datetime.datetime'>
--------------------------------------------------
2019-05-23    10:35:44 <class 'str'>
--------------------------------------------------
2019-05-23 10:35:44 <class 'datetime.datetime'>
--------------------------------------------------
2019-05-23 00:00:00 <class 'datetime.datetime'>
2019 <class 'str'>
2019-05-23 00:00:00 <class 'datetime.datetime'>
(2).时间格式化
%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.
(3).时间运算

datetime 或 date对象 之间可以进行减法运算,从而得到他们之间的时间间隔。

import time
from datetime import datetime

now1 = datetime.now()
time.sleep(3)
now2 = datetime.now()
delta = now2 - now1
print(delta)
********************************************************************
0:00:03.011656

from datetime import datetime, timedelta

today = datetime.now()
# 创建一个datetime对象
tomorrow = today + timedelta(days=1)	# 日时分秒毫秒微秒都可以
yesterday1 = today - timedelta(days=1)
yesterday2 = today + timedelta(days=-1)
print(today)
print(tomorrow)
print(yesterday1)
print(yesterday2)
***********************************************************************
2019-05-23 11:35:56.662744
2019-05-24 11:35:56.662744
2019-05-22 11:35:56.662744
2019-05-22 11:35:56.662744
(4).时区转换
from datetime import datetime, timedelta, timezone

tz = timezone(offset=timedelta(hours=8))
d = datetime.now(tz=tz)

new_tz = timezone(offset=timedelta(hours=5))
new_d = d.astimezone(tz=new_tz)
print(d)
print(new_d)
************************************************************************
2019-05-23 12:05:11.931991+08:00
2019-05-23 09:05:11.931991+05:00

二、logging模块

1.概述

logging是python的内置的日志模块,很多的第三方库,例如scrapy,django框架的日志记录都是使用logging模块。

等级

Logging中几种级别:DEBUG < INFO < WARNING <ERROR < CRITICAL

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

2.简单使用

logging 默认使用等级为warning

import logging


logging.debug('This is a debug log')
logging.info('This is a info log')
logging.warning('This is a waining log')
logging.error('This is a error log')
logging.critical('This is a critical log')
************************************************************************
WARNING:root:This is a waining log
ERROR:root:This is a error log
CRITICAL:root:This is a critical log
import logging      #  导入

logging.basicConfig(
    level=logging.DEBUG,        # 设置等级
    format="%(asctime)s-%(levelname)s-%(message)s"  # 设置输出格式
)


logging.debug('This is a debug log')
logging.info('This is a info log')
logging.warning('This is a warning log')
logging.error('This is a error log')
logging.critical('This is a critical log')
************************************************************************
2019-05-29 14:08:13,527-DEBUG-This is a debug log
2019-05-29 14:08:13,527-INFO-This is a info log
2019-05-29 14:08:13,527-WARNING-This is a warning log
2019-05-29 14:08:13,527-ERROR-This is a error log
2019-05-29 14:08:13,527-CRITICAL-This is a critical log

常用format格式化规则:

%(asctime)s日志事件发生的时间
%(levelname)s该日志记录的日志级别
%(message)s日志记录的文本内容
%(name)s所使用的日志器名称,默认是’root’
%(pathname)s调用日志记录函数的文件的全路径
%(filename)s调用日志记录函数的文件
%(funcName)s调用日志记录函数的函数名
%(lineno)d调用日志记录函数的代码所在的行号

format格式化规则:

Attribute nameFormatDescription
argsYou shouldn’t need to format this yourself.The tuple of arguments merged into msg to produce message, or a dict whose values are used for the merge (when there is only one argument, and it is a dictionary).
asctime%(asctime)sHuman-readable time when the LogRecord was created. By default this is of the form ‘2003-07-08 16:49:45,896’ (the numbers after the comma are millisecond portion of the time).
created%(created)fTime when the LogRecord was created (as returned by time.time()).
exc_infoYou shouldn’t need to format this yourself.Exception tuple (à la sys.exc_info) or, if no exception has occurred, None.
filename%(filename)sFilename portion of pathname.
funcName%(funcName)sName of function containing the logging call.
levelname%(levelname)sText logging level for the message ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL').
levelno%(levelno)sNumeric logging level for the message (DEBUG, INFO,WARNING, ERROR, CRITICAL).
lineno%(lineno)dSource line number where the logging call was issued (if available).
message%(message)sThe logged message, computed as msg % args. This is set when Formatter.format() is invoked.
module%(module)sModule (name portion of filename).
msecs%(msecs)dMillisecond portion of the time when the LogRecord was created.
msgYou shouldn’t need to format this yourself.The format string passed in the original logging call. Merged with args to produce message, or an arbitrary object (see Using arbitrary objects as messages).
name%(name)sName of the logger used to log the call.
pathname%(pathname)sFull pathname of the source file where the logging call was issued (if available).
process%(process)dProcess ID (if available).
processName%(processName)sProcess name (if available).
relativeCreated%(relativeCreated)dTime in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.
stack_infoYou shouldn’t need to format this yourself.Stack frame information (where available) from the bottom of the stack in the current thread, up to and including the stack frame of the logging call which resulted in the creation of this record.
thread%(thread)dThread ID (if available).
threadName%(threadName)sThread name (if available).

3.将日志写到文件

import logging      #  导入

logging.basicConfig(
    filename='example.log',		# 当前路径下的文件名
    level=logging.DEBUG,        # 等级
    format="%(asctime)s-%(levelname)s-%(message)s"  # 设置输出格式
)


logging.debug('This is a debug log')
logging.info('This is a info log')
logging.warning('This is a warning log')
logging.error('This is a error log')
logging.critical('This is a critical log')
************************************************************************
************************************************************************
example.log:
2019-05-29 14:17:46,486-DEBUG-This is a debug log
2019-05-29 14:17:46,486-INFO-This is a info log
2019-05-29 14:17:46,486-WARNING-This is a warning log
2019-05-29 14:17:46,486-ERROR-This is a error log
2019-05-29 14:17:46,486-CRITICAL-This is a critical log

4.高级用法

组件说明
Loggers(日志记录器)提供程序直接使用的接口
Handler(日志处理组件)将记录的日志发送到指定的位置
Filters(日志过滤器)用于过滤特定的日志记录
Formatters(日志格式器)用于控制日志信息的输出格式

步骤:

  1. 创建一个loggers对象
  2. 设置日志级别
  3. 创建formatters对象
  4. 定义handler对象,决定吧日志发送到哪里
  5. 设置handler的日志格式
  6. 将handler 添加到logger中
import logging      #  导入

#1. 创建一个loggers对象
logger = logging.getLogger('%s_log' % __name__)
#2. 设置日志级别
logger.setLevel(logging.INFO)
#3. 创建formatters对象
formatter = logging.Formatter('%(asctime)s - %(filename)s [line:%(lineno)d - %(levelname)s: %(message)s]')
#4. 定义handler对象,决定吧日志发送到哪里
fh = logging.FileHandler('example.log')		#写到文本的,参数为文件名
fh.setLevel(logging.WARNING)		# 设置文件级别

# 再创建一个handler输出日志到控制台
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
#5.设置handler的日志格式
fh.setFormatter(formatter)
ch.setFormatter(formatter)
#6.将handler 添加到logger中
logger.addHandler(fh)
logger.addHandler(ch)


data = '1.1'
logger.info('转换数据 %s 为整数' % data)
try:
    int(data)
except Exception as e:
    logger.error(e)
************************************************************************
2019-05-29 14:39:22,083 - text.py [line:29 - INFO: 转换数据 1.1 为整数]
2019-05-29 14:39:22,083 - text.py [line:33 - ERROR: invalid literal for int() with base 10: '1.1']
************************************************************************
************************************************************************
example.log:
2019-05-29 14:39:22,083 - text.py [line:33 - ERROR: invalid literal for int() with base 10: '1.1']
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这个报错是因为在logging.basicConfig()方法中,有一个格式字符串的语法错误,即datefmt参数的格式字符串中有一个“%”符号后面没有跟任何字符,应该把它改成“%H”。正确的格式字符串应该是'%Y-%m-%d %H:%M:%S'。修改后的代码如下: ```python from apscheduler.schedulers.blocking import BlockingScheduler from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR import datetime import logging logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', # 修改这里的格式字符串 filename='log1.txt', filemode='a') logging.FileHandler(encoding='utf-8', filename='log1.txt') def aps_test(x): print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x) def date_test(x): print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x) print(1/0) def my_listener(event): if event.exception: print('出错??????') else: print('正常///////////') scheduler = BlockingScheduler() scheduler.add_job(func=date_test, args=('一次性出错任务',), next_run_time=datetime.datetime.now()+datetime.timedelta(seconds=15), id='date_task') scheduler.add_job(func=aps_test, args=('循环任务',), trigger='interval', seconds=3, id='interval_task') scheduler.add_listener(my_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR) scheduler._logger=logging scheduler.start() ``` 注意:如果你在使用这段代码时,日期时间格式不需要秒数,可以将datefmt参数改为'%Y-%m-%d %H:%M'。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值