实际转换
日期范围计算
生成日期序列
from datetime import date, timedelta
def generate_date_range(start_date, end_date):
current = start_date
while current <= end_date:
yield current
current += timedelta(days=1)
start = date(2023, 1, 1)
end = date(2023, 1, 10)
for single_date in generate_date_range(start, end):
print(single_date)
日期操作技巧
年龄计算
from datetime import date
def calculate_age(birth_date):
today = date.today()
age = today.year - birth_date.year
## 如果今年生日还未到,则调整年龄
if (today.month, today.day) < (birth_date.month, birth_date.day):
age -= 1
return age
birth = date(1990, 5, 15)
print(f"当前年龄: {calculate_age(birth)}")
日期转换模式
graph TD
A[原始日期] --> B[转换]
B --> C[增加/减少天数]
B --> D[月的开始/结束]
B --> E[星期几]
B --> F[时区转换]
常见日期转换
转换 |
方法 |
示例 |
月的第一天 |
replace(day=1) |
获取月份开始 |
月的最后一天 |
自定义计算 |
找到最后一天 |
下一个工作日 |
自定义逻辑 |
跳过周末 |
财年开始 |
日期调整 |
与财年日历对齐 |
月末计算
from datetime import date
from calendar import monthrange
def get_last_day_of_month(year, month):
return date(year, month, monthrange(year, month)[1])
current_date = date.today()
last_day = get_last_day_of_month(current_date.year, current_date.month)
print(f"当前月份的最后一天: {last_day}")
高级日期转换
处理工作日
from datetime import date, timedelta
def next_business_day(input_date):
while input_date.weekday() >= 5: ## 5、6 分别是周六、周日
input_date += timedelta(days=1)
return input_date
today = date.today()
next_work_day = next_business_day(today)
print(f"下一个工作日: {next_work_day}")
日期比较策略
def is_weekend(check_date):
return check_date.weekday() >= 5
def is_holiday(check_date):
## 节假日逻辑的占位符
holidays = [
date(check_date.year, 1, 1), ## 元旦
date(check_date.year, 12, 25) ## 圣诞节
]
return check_date in holidays
current = date.today()
print(f"是否是周末: {is_weekend(current)}")
print(f"是否是节假日: {is_holiday(current)}")
LabEx Pro 提示
在执行复杂的日期转换时,LabEx 建议创建可重用的实用函数,以高效地处理常见的日期操作场景。
抗错误转换
def safe_date_transform(input_date, days_offset=0):
try:
transformed_date = input_date + timedelta(days=days_offset)
return transformed_date
except Exception as e:
print(f"转换错误: {e}")
return input_date