我是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
2 回答
find_month_first_monday
我会使用不同的算法 . 首先,找到该月的第一天 .
并找到
first_day_of_month
的工作日,并在必要时添加天数 .
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
weeks
.使用优秀的dateutil模块 . 用它做这个和其他日期计算非常容易 .
一些例子:
本月的第一个周五,为期10个月:
结果:
今年的第一个星期一,为期3年:
结果: