Skip to main content
 首页 » 编程设计

python之Python 中的日期计算

2025年05月04日16youxin

我对 Python 比较陌生,我正在尝试编写以下日期计算函数

  • 查找指定日期时间是/曾经是星期一的日期
  • 在指定的日期时间找到该月的第一个非周末
  • 查找指定日期时间中一年中的第一个非周末
  • 在指定日期时间找到一个月的第 N [星期几]

到目前为止,这是我的尝试 - 如果可以改进(或更正)逻辑以使其更“Pythonic”,请告诉我

import datetime 
 
def find_month_first_monday(tstamp = datetime.today()): 
    day_of_month = datetime.date.today().timetuple()[2] 
    day_of_week = datetime.weekday(tstamp) 
    # now I have the dow, and dom, I can index into a 2D array of 
    # dates for the month - IF I knew how to get to that array ... 
 
 
def find_first_gbd_in_month(tstamp = datetime.today()): 
    # naive way would be to find the month and year from the passed in arg, 
    # calculate the first day for that month/year and iterate until a non-weekend day 
    # is found. Not elegant, there must be a better way 
    pass 
 
 
def find_first_gbd_in_year(tstamp = datetime.today()): 
   # Ditto, as above. 
    pass 
 
 
def find_ndow_in_month(tstamp = datetime.today()): 
    # again, I can get the month and the year from the passed in argument 
    # what I need is a 2D array of dates for the month/year, so I can get 
    # the nth dow (similar to reading off a calendar) 
    pass 

请您参考如下方法:

find_month_first_monday

我会使用不同的算法。首先,找到该月的第一天。

first_day_of_month = datetime.date.today().replace(day=1) 

并找到 first_day_of_month 的星期几,

week_day = first_day_of_month.weekday() 

并在必要时添加天数。

if week_day: 
  first_day_of_month += datetime.timedelta(days=7-week_day) 

find_first_gbd_in_month

类似于 find_month_first_monday,但仅当 week_day 为 5 或 6(周六和周日)时才添加日期。

find_first_gbd_in_year

同时在 .replace 中提供 month=1 参数。

find_ndow_in_month

找到一周的第一天,然后添加 n-1 周。