在Python中生成日期可以通过多种方式实现,以下是几种常见的方法:
1. 使用`datetime`模块:
from datetime import date获取当前日期current_date = date.today()print(current_date)解析特定日期字符串date_str = '2023/02/24'date_obj = date.strptime(date_str, '%Y/%m/%d')print(date_obj)
2. 使用`time`模块:
import time获取当前时间戳current_timestamp = time.time()将时间戳转换为日期current_date = time.localtime(current_timestamp)print(time.strftime('%Y-%m-%d', current_date))

3. 使用`calendar`模块生成指定日期的日历:
import calendar输入指定年月yy = int(input("输入年份: "))mm = int(input("输入月份: "))显示日历print(calendar.month(yy, mm))
4. 使用第三方库`python-dateutil`:
from dateutil.parser import parsefrom dateutil.rrule import rrule, DAILY解析特定日期字符串date_str = '2023-02-24'date_obj = parse(date_str)print(date_obj)根据规则生成日期列表start_date = date_objend_date = date_obj + timedelta(days=365)for single_date in rrule(DAILY, dtstart=start_date, until=end_date):print(single_date.strftime('%Y-%m-%d'))
