ai
  • index
  • cursor
  • vector
  • crawl
  • crawl-front
  • DrissionPage
  • logging
  • mysql
  • pprint
  • sqlalchemy
  • contextmanager
  • dotenv
  • Flask
  • python
  • job
  • pdfplumber
  • python-docx
  • redbook
  • douyin
  • ffmpeg
  • json
  • numpy
  • opencv-python
  • pypinyin
  • re
  • requests
  • subprocess
  • time
  • uuid
  • watermark
  • milvus
  • pymilvus
  • search
  • Blueprint
  • flash
  • Jinja2
  • secure_filename
  • url_for
  • Werkzeug
  • chroma
  • HNSW
  • pillow
  • pandas
  • beautifulsoup4
  • langchain-community
  • langchain-core
  • langchain
  • langchain_unstructured
  • libreoffice
  • lxml
  • openpyxl
  • pymupdf
  • python-pptx
  • RAGFlow
  • tabulate
  • sentence_transformers
  • jsonl
  • collections
  • jieba
  • rag_optimize
  • rag
  • rank_bm25
  • Hugging_Face
  • modelscope
  • all-MiniLM-L6-v2
  • ollama
  • rag_measure
  • ragas
  • ASGI
  • FastAPI
  • FastChat
  • Jupyter
  • PyTorch
  • serper
  • uvicorn
  • markdownify
  • NormalizedLevenshtein
  • raq-action
  • CrossEncoder
  • Bi-Encoder
  • neo4j
  • neo4j4python
  • matplotlib
  • Plotly
  • Streamlit
  • py2neo
  • abc
  • read_csv
  • neo4jinstall
  • APOC
  • neo4jproject
  • uv
  • GDS
  • heapq
  • 1. 时间表示方式
  • 2. 常用函数
    • 获取当前时间
    • 时间转换
    • 时间格式说明符
    • 其他实用函数
  • 3. struct_time结构
  • 4. 实际应用示例
    • 计算代码执行时间
    • 格式化日志时间戳
    • 解析日期字符串
  • 5. 注意事项

time模块是Python标准库中用于处理时间的核心模块之一,它提供了各种与时间相关的函数。下面我将详细介绍time模块的主要功能和使用方法。

1. 时间表示方式 #

在Python中,时间通常有以下几种表示形式:

  • 时间戳(Timestamp):从1970年1月1日00:00:00 UTC开始计算的秒数(浮点数)
  • 结构化时间(struct_time):由9个元素组成的元组
  • 格式化字符串时间:如"2023-01-15 14:30:00"

2. 常用函数 #

获取当前时间 #

import time

# 获取当前时间戳(浮点数)
current_timestamp = time.time()
print(current_timestamp)  # 例如:1673789400.123456

# 获取当前结构化时间(本地时区)
local_time = time.localtime()
print(local_time)
# 输出类似:time.struct_time(tm_year=2023, tm_mon=1, tm_mday=15, tm_hour=14, tm_min=30, tm_sec=0, tm_wday=6, tm_yday=15, tm_isdst=0)

# 获取当前UTC时间
utc_time = time.gmtime()
print(utc_time)

时间转换 #

# 时间戳 → 结构化时间
struct_time = time.localtime(1673789400)

# 结构化时间 → 时间戳
timestamp = time.mktime(struct_time)

# 结构化时间 → 格式化字符串
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", struct_time)
print(formatted_time)  # 例如:"2023-01-15 14:30:00"

# 格式化字符串 → 结构化时间
parsed_time = time.strptime("2023-01-15 14:30:00", "%Y-%m-%d %H:%M:%S")

时间格式说明符 #

在strftime和strptime中使用的常见格式代码:

代码 含义 示例
%Y 四位数的年份 2023
%m 两位数的月份(01-12) 01
%d 两位数的日期(01-31) 15
%H 24小时制的小时(00-23) 14
%M 分钟(00-59) 30
%S 秒(00-59) 00
%A 星期全名 Sunday
%a 星期缩写 Sun
%B 月份全名 January
%b 月份缩写 Jan

其他实用函数 #

# 程序暂停(秒)
time.sleep(2.5)  # 暂停2.5秒

# 性能计时(用于测量代码执行时间)
start = time.perf_counter()
# 执行一些代码
end = time.perf_counter()
print(f"执行时间:{end - start}秒")

# 获取进程时间(CPU时间)
cpu_time = time.process_time()

3. struct_time结构 #

struct_time是一个具有命名元组接口的对象,包含以下9个属性:

  1. tm_year:年份(如2023)
  2. tm_mon:月份(1-12)
  3. tm_mday:日(1-31)
  4. tm_hour:小时(0-23)
  5. tm_min:分钟(0-59)
  6. tm_sec:秒(0-61,考虑闰秒)
  7. tm_wday:星期几(0-6,0是周一)
  8. tm_yday:一年中的第几天(1-366)
  9. tm_isdst:夏令时标志(-1, 0, 1)

4. 实际应用示例 #

计算代码执行时间 #

def some_function():
    time.sleep(1.5)  # 模拟耗时操作

start_time = time.time()
some_function()
end_time = time.time()
print(f"函数执行耗时:{end_time - start_time:.2f}秒")

格式化日志时间戳 #

log_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(f"[{log_time}] 这是一条日志信息")

解析日期字符串 #

date_str = "2023-01-15"
date_struct = time.strptime(date_str, "%Y-%m-%d")
print(f"解析后的年份:{date_struct.tm_year}")

5. 注意事项 #

  1. time.time()返回的时间戳是浮点数,表示从1970年1月1日UTC开始的秒数(Unix时间戳)
  2. time.sleep()的精度取决于操作系统,通常不适用于高精度计时
  3. 对于跨时区应用,建议使用UTC时间(time.gmtime())
  4. 在Python 3.3+中,time.perf_counter()提供了更高精度的计时

time模块适合处理简单的时间操作,对于更复杂的时间处理(如时区、日历操作等),建议使用datetime模块。

访问验证

请输入访问令牌

Token不正确,请重新输入