在下面的示例中-我们正在实现一个python程序来打印当前/今天的年,月和年。
步骤:
从datetime模块导入date类
创建今天的日期对象-调用 date类的 today() 函数以获取当前日期。
通过使用日期对象,我们可以提取和打印今天的年,月和日。
# Python程序 # 打印今天的年,月和日 # 导入日期类datetime模块 from datetime import date # 创建今天的日期的日期对象 current_date = date.today() # 打印当前日期 print("Current date: ", current_date) # 提取当前的年,月和日 print("Current year:", current_date.year) print("Current month:", current_date.month) print("Current day:", current_date.day)
输出结果
Current date: 2020-03-09 Current year: 2020 Current month: 3 Current day: 9