我构建了一个Date类,它有明天的方法,add_n_days方法,equals方法,方法之前和之后,以及差异方法。我想弄清楚的是如何使用我的差异方法来创建一个新方法,在那里我找出Date对象所在的星期几。
# A class to represent calendar dates
#
class Date:
""" A class that stores and manipulates dates,
represented by a day, month, and year.
"""
# The constructor for the Date class.
def __init__(self, new_month, new_day, new_year):
""" The constructor for objects of type Date. """
self.month = new_month
self.day = new_day
self.year = new_year
# The function for the Date class that returns a Date
# object in a string representation.
def __repr__(self):
""" This method returns a string representation for the
object of type Date that it is called on (named self).
** Note that this _can_ be called explicitly, but
it more often is used implicitly via printing or evaluating.
"""
s = '%02d/%02d/%04d' % (self.month, self.day, self.year)
return s
def is_leap_year(self):
""" Returns True if the called object is
in a leap year. Otherwise, returns False.
"""
if self.year % 400 == 0:
return True
elif self.year % 100 == 0:
return False
elif self.year % 4 == 0:
return True
return False
def copy(self):
""" Returns a new object with the same month, day, year
as the called object (self).
"""
new_date = Date(self.month, self.day, self.year)
return new_date
def is_before(self,d2):
if self.year<d2.year:
return true
if self.month<d1.month and self.year==d2.year:
return True
if self.day < d2.day and d2.month == self.month and self.year ==d2.year:
return true
return False
def is_after(self,d2):
return d2.isbefore(self)
def diff(self,d2):
dcopy=self.copy()
difference=0
if dcopy.isbefore(d2) == True:
while dcopy.isBefore(d)==true:
dcopy.tomorrow()
difference-=1
else:
while dcopy.isafter(d2):
dcopy.yesterday()
difference +=1
return difference
def diff(self,d2):
dcopy=self.copy()
difference=0
while dcopy.isbefore(d2):
dcopy.tomorrow()
difference-=1
while dcopy.isafter(d2):
dcopy.yesterday()
difference+=1
我正在考虑实施它的方式,但并不是真正理解如何具体建立它是一个已知日期,一个工作日列表,使用模数运算符来试图找出当天周 - %= 7,以及上面的差异(差异)方法。
我解决这个问题的最佳方式是什么,我将不胜感激任何帮助,解释 - 我是python和OOP的新手。
感谢。
day_of_week_names = [&#39;星期一&#39;,&#39;星期二&#39;,&#39;星期三&#39;&#39;星期四&#39;, &#39;星期五&#39;,&#39;星期六&#39;,&#39;星期天&#39;]
在shell中输出,我觉得应该是这样的
>>> d = Date(4, 4, 2016)
>>> d.day_of_week()
'Monday'
>>> Date(1, 1, 2100).day_of_week()
'Friday'
>>> Date(7, 4, 1776).day_of_week()
'Thursday'
答案 0 :(得分:3)
如果我告诉你,2000年1月1日是星期一,并问你50天后一周的哪一天,那很容易弄明白。
它只是50%7,即1。因此,我们知道我们所关注的一周中的某一天是我们知道的那一天。
所以50天后会是星期二,或者是星期一的1天。
由于您可以找出任何给定日期和所谓的锚定日期之间的天数(例如我上面给出的1/1/2000示例),您可以计算任何日期的星期几。 / p>
答案 1 :(得分:0)
wikipedia引用的以下伪代码应该可以帮助您入门。它取决于整数除法,所以记得在python中使用//
来获得'c-like'整数除法。
def day_of_week(self):
d, m, y = self.day, self.month, self.year
day_of_week_names = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
t = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]
if m < 3:
y -= 1
index = (y + y//4 - y//100 + y//400 + t[m-1] + d) % 7
return day_of_week_names[index]