在日志记录中使用strftime函数可以将日期时间格式化为特定的字符串格式。例如,可以使用以下方式将当前时间格式化为指定格式并记录到日志中:
import loggingimport datetime# 创建一个日志记录器logger = logging.getLogger('example_logger')logger.setLevel(logging.DEBUG)# 创建一个文件处理器,并设置日志记录级别为DEBUGfile_handler = logging.FileHandler('example.log')file_handler.setLevel(logging.DEBUG)# 创建一个格式化器,将时间格式化为指定格式formatter = logging.Formatter('%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')# 将格式化器添加到处理器中file_handler.setFormatter(formatter)# 将处理器添加到记录器中logger.addHandler(file_handler)# 记录一条日志消息logger.debug('This is a debug message')# 关闭日志记录器logging.shutdown()在上面的示例中,%(asctime)s使用strftime函数将时间格式化为'%Y-%m-%d %H:%M:%S'的字符串格式,并将其作为日志消息的一部分记录到日志中。


