亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> Python

Python datetime 模块精通:日期、时间、timedelta 与 strftime 详解

Python datetime 库提供了强大的工具集,用于操作日期、时间和时间间隔。通过面向对象而非原始字符串或时间戳,开发者能精确计算和格式化,信心满满。

datetime 核心类

入门:导入与实例化

操作前导入所需类:

from datetime import date, time, datetime, timedelta

实例化 date 对象:

today = date.today()
print(today)  # 例如 2024-04-19

获取当前日期和时间

datetime.now() 返回当前本地日期时间:

now = datetime.now()
print(now)  # 2024-04-19 14:35:12.123456

仅提取时间部分:

current_time = now.time()
print(current_time)  # 14:35:12.123456

使用 strftime 格式化输出

strftime 将 datetime 对象转为可读字符串,使用格式代码:

now.strftime("%Y-%m-%d %H:%M:%S")  # "2024-04-19 14:35:12"

常用指令:

示例:

# 12 小时制带 AM/PM
print(now.strftime("%I:%M:%S %p"))
# 24 小时制
print(now.strftime("%H:%M"))

使用 timedelta 进行时间运算

timedelta 表示时间跨度,支持与日期/时间加减:

# 创建 365 天的 timedelta
one_year = timedelta(days=365)
# 一年后的日期
future_date = datetime.now() + one_year
print(future_date)

计算距离事件天数(如新年):

today = date.today()
new_year = date(today.year, 1, 1)
if new_year < today:
    new_year = date(today.year + 1, 1, 1)
print("New Year is in", (new_year - today).days, "days")

综合示例脚本

下面脚本演示核心功能,可直接运行:

from datetime import datetime, date, timedelta
# 当前日期时间
now = datetime.now()
print("Now:", now)
# 格式化示例
print("ISO format:", now.strftime("%Y-%m-%d %H:%M:%S"))
print("12-hour time:", now.strftime("%I:%M:%S %p"))
# timedelta 运算
one_week = timedelta(weeks=1)
print("One week from now:", now + one_week)
# 距离新年天数
today = date.today()
new_year = date(today.year + (today < date(today.year, 1, 1)), 1, 1)
print("Days until New Year:", (new_year - today).days)

总结

Python datetime 模块为开发者提供强大、类型安全的日期时间操作工具:

这些工具从简单的时间戳记录到复杂的调度逻辑皆不可或缺。

Python

  1. 精通 Python datetime:日期、时间与时区实战指南
  2. Python 获取当前日期和时间:实用指南
  3. Python 轻松获取当前时间与时区数据
  4. 精通 Python time 模块:函数、结构体与实战示例
  5. 精通 Python time.sleep():最佳实践、多线程与实战案例
  6. Python print() 函数完全指南:基础用法、空行打印与自定义结束符
  7. Python str.count() 完全指南:统计字符与子串出现次数实战
  8. Python format() 字符串格式化完全指南:占位符、格式化规范、类与字典应用
  9. Python 字符串 find() 方法完全指南:语法、参数、替代方案与计数技巧
  10. 精通 Python Lambda 函数:实用示例与最佳实践
  11. Python round() 函数详解与实战示例
  12. 精通 Python map() 函数:语法、示例与最佳实践