python --生成区间内所有日期/计算两个日期相差多少天/近一周日期
def date_range(beginDate, endDate) -> list:
'''区间内所有日期'''
dates = []
dt = datetime.datetime.strptime(beginDate, "%Y-%m-%d")
date = beginDate[:]
while date <= endDate:
dates.append(date)
dt = dt + datetime.timedelta(1)
date = dt.strftime("%Y-%m-%d")
return dates
def date_range() -> list:
'''最近7天日期'''
before_date = datetime.timedelta(days=7)
today = datetime.datetime.today()
beginDate, endDate = str((today - before_date).date()), str(today.date())
dates = []
dt = datetime.datetime.strptime(beginDate, "%Y-%m-%d")
date = beginDate[:]
while date <= endDate:
dates.append(date)
dt = dt + datetime.timedelta(1)
date = dt.strftime("%Y-%m-%d")
return dates
print(date_range())
from datetime import datetime, timedelta
def get_first_and_last_day(year, month):
'''获取本月第一天和最后一天'''
first_day = datetime(year, month, 1)
if month == 12:
last_day = datetime(year + 1, 1, 1) - timedelta(days=1)
else:
last_day = datetime(year, month + 1, 1) - timedelta(days=1)
return first_day.date(), last_day.date()
year = 2025
month = 2
first_day, last_day = get_first_and_last_day(year, month)
print("First day of the month:", first_day) # 输出本月的第一天
print("Last day of the month:", last_day) # 输出本月的最后一天
import pandas as pd
print(pd.date_range('2022-02-25', '2022-03-02', freq='D')) # 取日期间隔
# DatetimeIndex(['2022-02-25', '2022-02-26', '2022-02-27', '2022-02-28',
# '2022-03-01', '2022-03-02'],
# dtype='datetime64[ns]', freq='D')
print(pd.date_range(start='2022-02-25', freq='D', periods=3)) # 只指定开始日期
# DatetimeIndex(['2022-02-25', '2022-02-26', '2022-02-27'], dtype='datetime64[ns]', freq='D')
print(pd.date_range(end='2022-02-25', freq='D', periods=3)) # 只指定结束日期
# DatetimeIndex(['2022-02-23', '2022-02-24', '2022-02-25'], dtype='datetime64[ns]', freq='D'
from datetime import datetime
def days_between_dates(date1_str, date2_str):
date_format = "%Y-%m-%d"
date1 = datetime.strptime(date1_str, date_format).date()
date2 = datetime.strptime(date2_str, date_format).date()
delta = date2 - date1
return delta.days
# 示例日期字符串
date1_str = "2023-01-01"
date2_str = "2023-01-10"
# 计算相差天数
days = days_between_dates(date1_str, date2_str) + 1
print(f"相差天数:{days} 天")