今天我们将探讨如何使用python进行时间和日期的操作。本文将重点介绍时间的加减法,涉及到的模块是
datetime
Part 1:实现功能

我们将实现以下功能:
Part 2:代码
立即学习“Python免费学习笔记(深入)”;

代码语言:Python 代码运行次数:0
运行 复制import datetime
<p>current_time = datetime.datetime.now()
print("当前时间:", current_time)
print("\n")</p><p>print("相差n天")
n = 3
time_delta = datetime.timedelta(days=n)
print("\n")</p><p>other_time = current_time + time_delta
tips = "{0}天后".format(n)
print(tips)
print(other_time)
print("\n")</p><p>other_time = current_time - time_delta
tips = "{0}天前".format(n)
print(tips)
print(other_time)
print("\n")</p><p>print("相差n小时")
n = 15
time_delta = datetime.timedelta(hours=n)
print("\n")</p><p>other_time = current_time + time_delta
tips = "{0}小时后".format(n)
print(tips)
print(other_time)
print("\n")</p><p>other_time = current_time - time_delta
tips = "{0}小时前".format(n)
print(tips)
print(other_time)代码截图

运行结果

Part 3:部分代码解读

current_time = datetime.datetime.now()
time_delta = datetime.timedelta(days=n)
datetime.timedelta
days
seconds
microseconds
milliseconds
minutes
hours
weeks
-
+
以上就是Python-时间及日期-04-时间加减法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号