Python 中带有日期时间模块的日期|部件
作者:互联网
我们可以使用两个类提取当前日期。
- 使用类
date
from datetime import date
today = date.today()
- 使用类
datetime
from datetime import datetime
today = datetime.today()
或
from datetime import datetime
now = datetime.now()
两者之间的主要区别是日期类只返回日期对象。而日期时间类不仅返回日期,还返回时间。date.today()
datetime.today()
使用 Python 提取当前日期、月份和年份
today = datetime.today()
print(f"Today: {today}")
print(f"Year: {today.year}")
print(f"Month: {today.month}")
print(f"Day: {today.day}")
输出:
Today: 2022-10-22 17:13:37.918735
Year: 2022
Month: 10
Day: 22
使用 Python 提取星期几
today = datetime.today()
print(f"Today: {today}")
print(f"Weekday: {today.weekday()}")
"""
OUTPUT:
Today: 2022-10-22 17:32:48.396792
Weekday: 5
"""
这个weekday() 方法将同时适用于 theandclass。date
datetime
注意:在这里,weekday() 方法将返回0到6 之间的索引。
使用Python提取当前时间
today = datetime.now()
print(f"Today: {today}")
print(f"Hour: {today.hour}")
print(f"Minute: {today.minute}")
print(f"Second: {today.second}")
输出:
Today: 2022-10-22 17:41:01.076569
Hour: 17
Minute: 41
Second: 1