网站首页 > 知识剖析 正文
大家好,我是钢铁老豆!快到五一了,每年到了这个时间点,就又该吐槽放假调休啦!真心不如不调,心累啊!言归正传,今天我们要聊聊Python是如何操作日期和时间的。
0. 模块简介
在Python中,处理日期和时间最常用的模块有三个:datetime、time和calendar。
- time模块:主要提供了时间的访问和转换。
- datetime模块:主要提供了日期和时间的算法。
- calendar模块:主要提供了广泛的方法来处理年历,如生成年历表格等。
1. time模块
主要与Unix时间戳相关联,表示从1970年1月1日00:00:00 UTC到现在的秒数。这个概念在很多编程语言中都很常见。
获取当前时间戳
import time
current_time = time.time()
print("当前时间戳:", current_time)
将时间戳转换为可读的时间格式
local_time = time.localtime(current_time)
readable_time = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
print("本地时间格式:", readable_time)
休眠(等待)
print("等待3秒钟...")
time.sleep(3)
print("完成等待!")
2. datetime模块
顾名思义,包含常见的日期和时间操作:
获取当前日期和时间
from datetime import datetime
now = datetime.now()
print("当前时间:", now)
格式化日期和时间
now_formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print("格式化后的时间:", now_formatted)
计算时间差
from datetime import timedelta
two_days_before = now - timedelta(days=2)
print("两天前的时间:", two_days_before)
3.calendar模块
主要用于生成和使用日历
import calendar
cal = calendar.month(2024, 1) # 生成2024年1月的日历
print("2024年1月的日历:\n", cal)
4. 完整参考
要深入学习这些模块的更多功能,可以访问Python的官方文档:
- time模块官方文档:https://docs.python.org/3/library/time.html
- datetime模块官方文档:https://docs.python.org/3/library/datetime.html
- calendar模块官方文档:https://docs.python.org/3/library/calendar.html
希望今天的分享对你有所帮助!如果觉得有用,不妨点个赞、收藏、留言或关注我吧!每天学习一点Python小知识,这里有你感兴趣的基础、技能、数据、模型和AI。我是钢铁老豆,一个30岁转行IT、自学成为算法工程师、想用AI点亮孩子小小世界的Pythoner。
猜你喜欢
- 2025-03-20 DATEVALUE与TIMEVALUE函数:日期时间数值转换
- 2025-03-20 第4天:《日期数据处理太复杂?秒懂时间序列操作的高效方法!》
- 2025-03-20 紧急无线电示位标,你用对了吗?(紧急无线电示位标用法)
- 2025-03-20 Java Date Time 教程-java.util.Date
- 2025-03-20 Python的datetime库 精准获取、转换和格式化日期与时间!
- 2025-03-20 Python 基础教程十八之 Python datetime模块
- 2025-03-20 使用 C# 解析月份简写的时间日期格式
- 2025-03-20 数据库日期类型使用Varchar与DateTime优缺点
- 2025-03-20 java 判断Date是上午还是下午(java判断当前时间是上午还是下午)
- 2025-03-20 SQLite - 日期时间函数 - UNIXEPOCH
- 最近发表
- 标签列表
-
- xml (46)
- css animation (57)
- array_slice (60)
- htmlspecialchars (54)
- position: absolute (54)
- datediff函数 (47)
- array_pop (49)
- jsmap (52)
- toggleclass (43)
- console.time (63)
- .sql (41)
- ahref (40)
- js json.parse (59)
- html复选框 (60)
- css 透明 (44)
- css 颜色 (47)
- php replace (41)
- css nth-child (48)
- min-height (40)
- xml schema (44)
- css 最后一个元素 (46)
- location.origin (44)
- table border (49)
- html tr (40)
- video controls (49)