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


相关推荐
巴里巴气11 分钟前
selenium基础知识 和 模拟登录selenium版本
爬虫·python·selenium·爬虫模拟登录
198915 分钟前
【零基础学AI】第26讲:循环神经网络(RNN)与LSTM - 文本生成
人工智能·python·rnn·神经网络·机器学习·tensorflow·lstm
JavaEdge在掘金21 分钟前
Redis 数据倾斜?别慌!从成因到解决方案,一文帮你搞定
python
ansurfen25 分钟前
我的第一个AI项目:从零搭建RAG知识库的踩坑之旅
python·llm
前端付豪30 分钟前
20、用 Python + API 打造终端天气预报工具(支持城市查询、天气图标、美化输出🧊
后端·python
前端付豪35 分钟前
19、用 Python + OpenAI 构建一个命令行 AI 问答助手
后端·python
amazinging1 小时前
北京-4年功能测试2年空窗-报培训班学测开-第四十三天
python·学习
wgyang20162 小时前
我的第一个LangFlow工作流——复读机
python
Zhen (Evan) Wang2 小时前
(豆包)xgb.XGBRegressor 如何进行参数调优
开发语言·python
我爱一条柴ya2 小时前
【AI大模型】线性回归:经典算法的深度解析与实战指南
人工智能·python·算法·ai·ai编程