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


相关推荐
七牛开发者7 小时前
为什么 Go 很适合 AI 辅助开发?
数据库·人工智能·python·elasticsearch·log4j
河南凹凸环境艺术设计8 小时前
性价比高的民宿酒店设计企业
大数据·人工智能·python
wuyk55511 小时前
Python 第三章:列表 List
服务器·开发语言·python
笨鸟先飞,勤能补拙11 小时前
从预测到决策:人工智能与机器学习的系统方法、工程闭环与现实边界
大数据·人工智能·windows·python·机器学习·密码学
MgArcher11 小时前
抖音a_bogus参数逆向实战:JSVMP环境模拟与Hook技术(2025最新)
javascript·爬虫·python
circuitsosk12 小时前
AI输出的“质检员”:构建智能体质量评估、异常检测与人工兜底的三层防线
人工智能·python·microsoft·正则表达式·langchain
要努力点12 小时前
Python入门第六课
开发语言·python
CTA终结者12 小时前
先用小策略练清条件和动作
人工智能·python
Bruce_Liuxiaowei12 小时前
从零到可运行:基于 Vue3 + FastAPI + DeepSeek-V3 的 AI 英语单词学习系统全栈实战
人工智能·python·学习·fastapi·全栈·智能体
ValhallaCoder12 小时前
Leetcode-hot100(2026.08.17)
python·算法·leetcode