在Python中,获取系统日期的年月日信息主要通过datetime
模块实现,具体方法如下:
一、核心方法
-
使用
datetime.now()
获取当前日期时间该函数返回一个
datetime
对象,包含年、月、日、时、分、秒等信息。from datetime import datetime now = datetime.now() print(now) # 输出类似:2025-05-06 14:30:00.123458
-
提取年、月、日属性 通过
year
、month
、day
属性分别获取年份、月份和日期。 ```python year = now.year month = now.month day = now.day print(f"当前日期:{year}年{month}月{day}日") # 输出:2025年5月6日 -
格式化输出
使用
strftime
方法将日期对象转换为指定格式的字符串。-
格式化年月日:
now.strftime("%Y-%m-%d")
→2025-05-06
-
格式化年月:
now.strftime("%Y-%m")
→2025-05
-
格式化日期:
now.strftime("%Y-%m-%d %H:%M:%S")
→2025-05-06 14:30:00
formatted_date = now.strftime("%Y-%m-%d") print(formatted_date) # 输出:2025-05-06
-
二、其他相关模块
-
time
模块 :提供低级时间函数,如time.localtime()
可获取本地时间结构体,但需手动提取年月日。 -
calendar
模块 :用于处理日历相关功能,如打印月份日历,但不直接提供日期截取功能。### 三、注意事项 -
datetime.now()
默认获取本地时间,若需处理时区,可结合pytz
模块使用。 -
日期对象支持数学运算(如加减天数),但需注意时区影响。
以上方法适用于大多数场景,建议优先使用datetime
模块的now
方法和属性进行日期截取与格式化。