我需要在python中计算一周的日期
我需要这个
year = 2012
week = 23
(a,b) = func (year,week)
print a
print b
>>>2012-04-06
>>>2012-06-10
你能帮帮我吗?
答案 0 :(得分:12)
日期对象包含weekday()
方法。
星期日6日为星期六返回0。
(来自谷歌搜索)这里有一个解决方案:http://www.protocolostomy.com/2010/07/06/python-date-manipulation/)
我认为这可以减少冗长,所以这是我的抨击:
def week_magic(day):
day_of_week = day.weekday()
to_beginning_of_week = datetime.timedelta(days=day_of_week)
beginning_of_week = day - to_beginning_of_week
to_end_of_week = datetime.timedelta(days=6 - day_of_week)
end_of_week = day + to_end_of_week
return (beginning_of_week, end_of_week)
答案 1 :(得分:5)
很少有过时的答案,但有一个名为isoweek的好模块真的可以完成。要回答原始问题,您可以执行以下操作:
from isoweek import Week
week = Week(2012, 23)
print(week.monday())
print(week.sunday())
希望这有助于任何人。
答案 2 :(得分:3)
我认为@Anthony Sottile的答案应该是这样的:
def week_magic(day):
day_of_week = day.weekday()
to_beginning_of_week = datetime.timedelta(days=day_of_week)
beginning_of_week = day - to_beginning_of_week
to_end_of_week = datetime.timedelta(days=6 - day_of_week)
end_of_week = day + to_end_of_week
return (beginning_of_week, end_of_week)
有效!