本文目录导读:

Python 获取系统当前时间有多种方式,以下是最常用的方法:
使用 datetime 模块(推荐)
from datetime import datetime
# 获取当前日期时间
now = datetime.now()
print("当前时间:", now)
# 格式化输出
print("格式化:", now.strftime("%Y-%m-%d %H:%M:%S"))
print("日期:", now.strftime("%Y年%m月%d日"))
print("时间:", now.strftime("%H:%M:%S"))
使用 time 模块
import time
# 获取时间戳(秒)
timestamp = time.time()
print("时间戳:", timestamp)
# 获取本地时间元组
local_time = time.localtime()
print("本地时间:", time.asctime(local_time))
# 格式化输出
print("格式化:", time.strftime("%Y-%m-%d %H:%M:%S", local_time))
获取特定时间元素
from datetime import datetime
now = datetime.now()
# 分别获取各个元素
year = now.year
month = now.month
day = now.day
hour = now.hour
minute = now.minute
second = now.second
microsecond = now.microsecond
print(f"年份: {year}")
print(f"月份: {month}")
print(f"日: {day}")
print(f"时: {hour}")
print(f"分: {minute}")
print(f"秒: {second}")
print(f"微秒: {microsecond}")
常用格式化符号
| 符号 | 含义 | 示例 |
|---|---|---|
| %Y | 4位年份 | 2024 |
| %m | 月份(01-12) | 08 |
| %d | 日(01-31) | 15 |
| %H | 24小时制(00-23) | 14 |
| %M | 分钟(00-59) | 30 |
| %S | 秒(00-59) | 45 |
| %A | 星期全称 | Monday |
| %a | 星期缩写 | Mon |
| %B | 月份全称 | August |
| %b | 月份缩写 | Aug |
完整示例
from datetime import datetime
def get_current_time():
"""获取并显示当前时间的多种格式"""
now = datetime.now()
print("=== 当前时间信息 ===")
print(f"完整时间: {now}")
print(f"日期: {now.strftime('%Y-%m-%d')}")
print(f"时间: {now.strftime('%H:%M:%S')}")
print(f"完整格式: {now.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"中文格式: {now.strftime('%Y年%m月%d日 %H点%M分%S秒')}")
# 判断上午/下午
if now.hour < 12:
period = "上午"
elif now.hour < 18:
period = "下午"
else:
period = "晚上"
print(f"现在是{period}")
if __name__ == "__main__":
get_current_time()
最常用的是 datetime.now(),因为它返回的对象可以直接访问年、月、日、时、分、秒等属性,也可以轻松格式化输出。