【Python】time模块

专栏文章索引:Python

目录

一、介绍​编辑

二、常用函数​编辑


一、介绍

Python 的 time 模块提供了处理时间的函数。

二、常用函数****

1.time():返回当前时间的时间戳(从1970年1月1日开始计时的秒数)。

python 复制代码
import time

current_time = time.time()
print(current_time)  # 1709996003.645545

那为什么从970年1月1日开始计时呢?

1970年1月1日被称为"Unix纪元(Unix Epoch)",它被广泛接受为计算机系统中的标准时间起点。Unix操作系统在设计之初选择1970年1月1日作为起始时间是因为以下几个原因:

  1. 时间简洁性:1970年1月1日没有任何特殊的历史事件或政治纠纷,这样可以使时间起点保持简洁和中立。

  2. 32位整数范围:Unix使用32位有符号整数来表示时间戳,而1970年1月1日是一个很方便的起点,可以涵盖几十年的时间范围。

  3. 兼容性:Unix操作系统在当时的计算机界非常流行,选择1970年1月1日作为时间起点可以使其他系统在时间表示上与Unix兼容。

从那时起,许多操作系统和编程语言都采用了类似的时间起点,因此UNIX纪元被广泛接受为计算机系统中的标准时间起点,并成为了时间表示的共同基准。

2.ctime():将一个时间戳转换为一个可读的字符串形式。

python 复制代码
import time

current_time = time.time()
readable_time = time.ctime(current_time)
print(readable_time)  # Sat Mar  9 14:55:21 2024

time.ctime() 函数返回的时间是基于 UTC 时间的,因此在某些时区下可能会导致输出的时间与本地时间相差若干小时
GMT时间:Greenwich Mean Time,格林尼治平时,又称格林尼治平均时间或格林尼治标准时间。是指位于英国伦敦郊区的皇家格林尼治天文台的标准时间。

UTC时间:Universal Time Coordinated,中文名称:世界标准时间或世界协调时。

UNIX时间戳(timestamp)计算机中的UNIX时间戳 ,是以GMT/UTC时间1970-01-01T00:00:00为起点,到当前具体时间的秒数(不考虑闰秒)。这样做的目的,主要是通过"整数计算"来简化计算机对时间操作的复杂度。

所以求当地时间还得根据区时计算。

3.sleep(secs):让程序休眠指定秒数。

python 复制代码
import time

print("开始休眠")
time.sleep(5)  # 休眠5秒
print("休眠结束")

4.gmtime():将一个时间戳转换为 UTC 时区的 struct_time 对象。

python 复制代码
import time

current_time = time.time()
utc_time = time.gmtime(current_time)
print(utc_time)  # time.struct_time(tm_year=2024, tm_mon=3, tm_mday=9, tm_hour=15, tm_min=11, tm_sec=22, tm_wday=5, tm_yday=69, tm_isdst=0)

** 5.localtime():**将一个时间戳转换为本地时区的 struct_time 对象。

python 复制代码
import time

current_time = time.time()
local_time = time.localtime(current_time)
print(local_time)  # time.struct_time(tm_year=2024, tm_mon=3, tm_mday=9, tm_hour=15, tm_min=11, tm_sec=58, tm_wday=5, tm_yday=69, tm_isdst=0)

struct_time格式,它包含了许多元素,这些元素的值都是通过浮点数来提供的

struct_time字母元素含意:

|----------|--------|------------|
| 元素 | 含义 | 取值 |
| tm_year | 年 | 4位数字,如2024 |
| tm_mon | 月 | 1~12,如2 |
| tm_mday | 日 | 1~31,如2 |
| tm_hour | 时 | 0~23,如7 |
| tm_min | 分 | 0~59,如50 |
| tm_sec | 秒 | |
| tm_wday | 一周的第几日 | |
| tm_yday | 一年的第几日 | |
| tm_isdst | 夏令时 | |


相关推荐
会员源码网1 小时前
Python中生成器函数与普通函数的区别
python
Java水解2 小时前
Python开发从入门到精通:Web框架Django实战
后端·python
曲幽3 小时前
FastAPI + PostgreSQL 实战:给应用装上“缓存”和“日志”翅膀
redis·python·elasticsearch·postgresql·logging·fastapi·web·es·fastapi-cache
Lupino6 小时前
别再只聊 AI 写代码了:技术负责人要把“变更治理”提到第一优先级
python·docker·容器
Flittly8 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(6)Context Compact (上下文压缩)
python·agent
曲幽19 小时前
FastAPI + PostgreSQL 实战:从入门到不踩坑,一次讲透
python·sql·postgresql·fastapi·web·postgres·db·asyncpg
用户8356290780511 天前
使用 C# 在 Excel 中创建数据透视表
后端·python
码路飞1 天前
FastMCP 实战:一个 .py 文件,给 Claude Code 装上 3 个超实用工具
python·ai编程·mcp
dev派1 天前
AI Agent 系统中的常用 Workflow 模式(2) Evaluator-Optimizer模式
python·langchain
前端付豪1 天前
AI 数学辅导老师项目构想和初始化
前端·后端·python