Python 当前标准时间显示
1. 简介
当前标准时间是指以协调世界时(UTC)为基准的时间。在 Python 中,我们可以使用内置的 datetime
模块来获取和操作当前标准时间。
本文将详细介绍如何使用 Python 来显示当前标准时间,并展示一些常见的时间格式化技巧。
2. datetime 模块
Python 的 datetime
模块提供了处理日期和时间的各种函数和类。在使用之前,我们需要导入该模块。
import datetime
3. 获取当前标准时间
使用 datetime
模块中的 datetime
类,我们可以轻松地获取当前标准时间。
import datetime
current_time = datetime.datetime.utcnow()
print(f"当前标准时间:{current_time}")
运行结果如下所示:
当前标准时间:2022-10-20 06:30:15.123456
4. 格式化当前标准时间
通常情况下,我们希望以一种更具可读性的格式显示当前标准时间。下面是一些常见的时间格式化代码:
- 显示年月日
current_time = datetime.datetime.utcnow()
formatted_time = current_time.strftime("%Y-%m-%d")
print(f"当前标准时间(年月日):{formatted_time}")
输出结果为:
当前标准时间(年月日):2022-10-20
- 显示年月日时分秒
current_time = datetime.datetime.utcnow()
formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
print(f"当前标准时间(年月日时分秒):{formatted_time}")
输出结果为:
当前标准时间(年月日时分秒):2022-10-20 06:30:15
除了上述示例中使用的 %Y
(年份)、%m
(月份)、%d
(日期)、%H
(小时)、%M
(分钟)、%S
(秒数) 之外,还有其他格式化代码。完整的列表可以在 Python 官方文档 中找到。
5. 星期几的显示
除了日期和时间之外,我们也可以使用 datetime
类来获取当前是星期几。
current_time = datetime.datetime.utcnow()
weekday = current_time.strftime("%A")
print(f"今天是星期:{weekday}")
输出结果为:
今天是星期:Thursday
上述示例中的 %A
表示星期几的全名,如果想要缩写形式,可以使用 %a
。
6. 总结
通过使用 Python 的 datetime
模块,我们可以轻松地获取和格式化当前标准时间。在实际中,很多应用场景都需要准确的时间戳和时间显示,而 datetime
模块提供的功能正好能够满足这些需求。