python中的time,datetime,logger模块

本文详细介绍了Python中时间处理的各种方法,包括获取时间戳、格式化日期、时间加减运算等,并演示了如何使用logging模块进行有效的日志记录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

      以前学python的时候,里面关于时间的模块学的很糙,没太明白,所以今天又复习了一下,记了一下笔记

# -*- coding: utf-8 -*-

import time,datetime

t = time.time() #返回当前时间戳
print(t)

t2 = time.ctime()  #返回当前时间字符串 星期几 几月几号
print(t2)
t3 = time.ctime(time.time()-86400)  #减去一天
print(t3)

print(''.center(40,'-'))
t4 = time.gmtime() #将时间转换成struct_time格式   默认格林尼治时间
print(t4)

time_str = '{year}-{month}-{day} {hour}:{minute}:{second}'.format(year=t4.tm_year,
                                                                  month=t4.tm_mon,
                                                                  day=t4.tm_mday,
                                                                  hour=t4.tm_hour,
                                                                  minute=t4.tm_min,
                                                                  second=t4.tm_sec)
print(time_str)

#获得本地时区的格式化时间
t5 = time.localtime()
local_time_str = '{year}-{month}-{day} {hour}:{minute}:{second}'.format(year=t5.tm_year,
                                                                  month=t5.tm_mon,
                                                                  day=t5.tm_mday,
                                                                  hour=t5.tm_hour,
                                                                  minute=t5.tm_min,
                                                                  second=t5.tm_sec)
print(local_time_str)
print(''.center(40,'-'))

t6 = time.mktime(t4)  #将一个时间对象 转成时间戳
print(t6)

#输出你想要的时间字符串样式
time_str_type = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
print(time_str_type,type(time_str_type))  #字符串

# 转成 struct_time 时间格式
time_obj_type = time.strptime(time_str_type,'%Y-%m-%d %H:%M:%S')
print(time_obj_type,type(time_obj_type))
print(time.mktime(time_obj_type))  #转成时间戳

print(''.center(40,'-'))
current_time = datetime.date.today()
print(current_time)  #输出格式 2016-09-03
print(time.time())  #输出时间戳
print(datetime.date.fromtimestamp(time.time()))  #将时间戳转成时期格式
print(datetime.datetime.now())  #输出当前时间
print(current_time.timetuple())  #返回struct_time 格式时间

print(''.center(40,'-'))

#将字符串转成时期格式
str_to_date = datetime.datetime.strptime('1/9/16 14:30:26','%d/%m/%y %H:%M:%S')
print(str_to_date)

new_date = datetime.datetime.now() + datetime.timedelta(days=10)#比现在加10天
print(new_date,'比现在加10天')

new_date = datetime.datetime.now() + datetime.timedelta(days=-10)#比现在减去10天
print(new_date,'比现在减去10天')


new_date = datetime.datetime.now() + datetime.timedelta(hours=10)#比现在加10个小时
print(new_date,'比现在加10个小时')

print(datetime.datetime.now(),'现在时间')

new_date = datetime.datetime.now() + datetime.timedelta(seconds=120)#比现在加120秒
print(new_date,'比现在加120秒')


 日志(logger)也是我们开发中经常用到的东西,代码如下

# -*- coding: utf-8 -*-

import logging

#create logger
logger = logging.getLogger('TEST-LOG')  #创建log对象
logger.setLevel(logging.INFO)  #设置全局的日志级别   其他日志级别只能比我高 不能比我低


# create console handler and set level to debug
console_log = logging.StreamHandler()   #输出到控制台(屏幕)
console_log.setLevel(logging.DEBUG)  #debug及以上级别开始

# create file handler and set level to warning
file_log = logging.FileHandler("access.log")  #输出到文件
file_log.setLevel(logging.WARNING) #warning及以上级别开始

# create formatter
formatter_console = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')  #格式化的样子
formatter_file =  logging.Formatter('%(asctime)s - %(filename)s '
                                    '- %(funcName)s- %(lineno)d- '
                                    '-%(levelname)s - %(message)s')

# add formatter to ch and fh
console_log.setFormatter(formatter_console)  #设置输出到屏幕的日志格式化
file_log.setFormatter(formatter_file)  #输出到文件的日志格式化

# add ch and fh to logger
logger.addHandler(console_log)  #创建的输出到控制台的logger对象注册到全局对象里面
logger.addHandler(file_log)      #创建的输出到文件的logger对象注册到全局对象里面

# 'application' code  级别从低到高
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')


<think>好的,我需要回答用户关于Python中用于时间记录的模块或方法的问题。首先,用户提到了“time logging”,可能指的是记录时间相关的信息,比如程序执行时间、事件时间戳等。我需要从Python标准库中寻找相关模块,并参考用户提供的引用内容。 首先,用户提供的引用[1]、[2]、[3]、[4]都涉及logging模块的使用,说明用户可能已经了解logging的基本用法,但需要更具体的时间记录方法。此外,用户的问题中提到了“time logging module or method”,可能需要结合时间处理和日志记录两方面。 Python标准库中的time模块datetime模块是处理时间的常用工具。time模块提供时间获取和格式化的功能,比如time.time()用于获取时间戳,time.strftime()用于格式化时间。datetime模块则更适合处理日期和时间的对象,例如记录事件的开始和结束时间。 接下来,logging模块本身已经支持在日志中自动添加时间戳,通过配置格式化字符串中的%(asctime)s即可,如引用[3]和[4]中的例子所示。用户可能希望了解如何自定义时间格式,或者在日志中记录特定事件的时间信息。 另外,如果需要测量代码块的执行时间,可以使用timeit模块,或者在代码中使用time模块计算时间差。例如,使用time.time()记录开始和结束时间,然后计算差值。 还需要考虑用户的实际应用场景,比如Web应用中的请求耗时记录,这时可能需要结合中间件或装饰器来记录时间。例如在Flask中,可以使用before_request和after_request钩子来计算处理时间,并用logging记录。 用户提供的引用[2]提到自定义Filter类,可能用户有更复杂的需求,比如按模块过滤日志,但当前问题集中在时间记录上,所以这部分可能暂时不需要深入。 总结回答的结构: 1. time模块:获取时间戳、格式化时间、计算时间差。 2. datetime模块:处理日期时间对象,更友好的时间操作。 3. logging模块的时间记录:配置asctime,自定义时间格式。 4. timeit模块:测量代码执行时间。 5. 实际应用示例:在函数或Web应用中使用上述方法记录时间。 需要确保每个部分都提供具体的代码示例,并引用用户提供的例子中的相关部分,比如logging的配置方法。同时,生成的相关问题要围绕这些模块的深入使用、性能分析、优化等。</think>在Python中处理时间记录主要涉及以下几个标准库模块,这些方法可以满足不同场景下的时间记录需求: ### 一、time模块基础方法 1. **获取时间戳** ```python import time start_time = time.time() # 记录开始时间戳 # 执行代码 end_time = time.time() print(f"执行耗时: {end_time - start_time:.2f}秒") ``` 该方法适用于计算代码段执行时间[^4] 2. **格式化时间输出** ```python formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print(f"当前时间: {formatted_time}") ``` ### 二、datetime模块(推荐) ```python from datetime import datetime # 记录带时区的时间 now = datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%f%z") print(f"ISO8601格式时间: {now}") # 计算时间差 start = datetime.now() # 执行操作 delta = datetime.now() - start print(f"耗时: {delta.total_seconds()}秒") ``` ### 三、logging模块集成 在日志中自动记录时间戳(引用[3][^3]的扩展): ```python import logging logging.basicConfig( format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO ) logger = logging.getLogger(__name__) logger.info("订单创建时间: %s", datetime.now().isoformat()) ``` ### 四、timeit模块(性能测试) ```python import timeit code_to_test = """ def example(): return sum(range(1000000)) example() """ execution_time = timeit.timeit(code_to_test, number=100) print(f"平均执行时间: {execution_time/100:.4f}秒") ``` ### 五、实际应用示例 **Web请求耗时记录(Flask示例)**: ```python from flask import Flask, g import time app = Flask(__name__) @app.before_request def record_start_time(): g.start_time = time.time() @app.after_request def log_request_time(response): duration = (time.time() - g.start_time) * 1000 # 毫秒 app.logger.info(f"请求耗时: {duration:.2f}ms") return response ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值