我对Python比较陌生,我正在尝试编写以下日期计算函数
这是我到目前为止的尝试 - 如果逻辑可以改进(或纠正)为更多'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
答案 0 :(得分:4)
我会使用不同的算法。首先,找到该月的第一天。
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_month_first_monday
类似,但仅在week_day
为5或6(星期六和星期日)时添加日期。
同时在month=1
中提供.replace
参数。
查找一周的第一天,然后添加n-1 weeks
。
答案 1 :(得分:4)
使用优秀的dateutil
模块。用它做这个和其他日期计算非常容易。
一些例子:
import datetime
from dateutil import rrule
today = datetime.date.today()
本月的第一个周五,为期10个月:
print list(rrule.rrule(rrule.MONTHLY, count=10, byweekday=rrule.FR(1),
dtstart=today)))
结果:
[datetime.datetime(2010, 8, 2, 0, 0),
datetime.datetime(2010, 9, 6, 0, 0),
datetime.datetime(2010, 10, 4, 0, 0),
datetime.datetime(2010, 11, 1, 0, 0),
datetime.datetime(2010, 12, 6, 0, 0),
datetime.datetime(2011, 1, 3, 0, 0),
datetime.datetime(2011, 2, 7, 0, 0),
datetime.datetime(2011, 3, 7, 0, 0),
datetime.datetime(2011, 4, 4, 0, 0),
datetime.datetime(2011, 5, 2, 0, 0)]
一年中的第一个星期一,为期3年:
print list(rrule.rrule(rrule.YEARLY, count=3, byweekday=rrule.MO(1),
dtstart=datetime.date.today()))
结果:
[datetime.datetime(2011, 1, 3, 0, 0),
datetime.datetime(2012, 1, 2, 0, 0),
datetime.datetime(2013, 1, 7, 0, 0)]