【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 | 夏令时 | |


相关推荐
TF男孩2 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
该用户已不存在7 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP9 小时前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
用户83562907805114 小时前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
c8i15 小时前
python中类的基本结构、特殊属性于MRO理解
python
liwulin050615 小时前
【ESP32-CAM】HELLO WORLD
python
Doris_202315 小时前
Python条件判断语句 if、elif 、else
前端·后端·python
Doris_202316 小时前
Python 模式匹配match case
前端·后端·python
这里有鱼汤16 小时前
Python量化实盘踩坑指南:分钟K线没处理好,小心直接亏钱!
后端·python·程序员
大模型真好玩17 小时前
深入浅出LangGraph AI Agent智能体开发教程(五)—LangGraph 数据分析助手智能体项目实战
人工智能·python·mcp