implementing a calendar class | Member | | Join Date: Sep 2007
Posts: 90
| | |
I would like to write a class CalculationDate which can deal with a date in numerical formation and text format and I have a nextDate method that returns the next day of the year. This class is written with a unit test which can test the proper treatment of leap year.
My question is how can I able to write a code to deal with the numerical formation and text format? I usually write a numerical one then write a function to convert it to text. If possible, can some one give an example code?
|  | Moderator | | Join Date: Sep 2006 Location: Minden, Nevada, USA
Posts: 6,400
| | | re: implementing a calendar class Quote:
Originally Posted by python101 I would like to write a class CalculationDate which can deal with a date in numerical formation and text format and I have a nextDate method that returns the next day of the year. This class is written with a unit test which can test the proper treatment of leap year.
My question is how can I able to write a code to deal with the numerical formation and text format? I usually write a numerical one then write a function to convert it to text. If possible, can some one give an example code? isinstance() is the prefered way to handle parameters which may have different types: -
>>> import time
-
>>> timeStr = time.asctime()
-
>>> timeStr
-
'Tue Nov 13 09:57:26 2007'
-
>>> timeTup = time.localtime()
-
>>> timeTup
-
(2007, 11, 13, 10, 1, 43, 1, 317, 0)
-
>>> class SmartTime(object):
-
... def DateAndTime(self, timeStrOrTup):
-
... if isinstance(timeStrOrTup, str):
-
... return timeStrOrTup
-
... if isinstance(timeStrOrTup, time.struct_time):
-
... return time.strftime("%a %b %d %H:%M:%S %Y", timeStrOrTup)
-
...
-
>>> st = SmartTime()
-
>>> st.DateAndTime(timeStr)
-
'Tue Nov 13 09:57:26 2007'
-
>>> st.DateAndTime(timeTup)
-
'Tue Nov 13 10:01:43 2007'
-
>>>
|  | Moderator | | Join Date: Sep 2006 Location: Minden, Nevada, USA
Posts: 6,400
| | | re: implementing a calendar class Quote:
Originally Posted by bartonc isinstance() is the prefered way to handle parameters which may have different types: -
>>> import time
-
>>> timeStr = time.asctime()
-
>>> timeStr
-
'Tue Nov 13 09:57:26 2007'
-
>>> timeTup = time.localtime()
-
>>> timeTup
-
(2007, 11, 13, 10, 1, 43, 1, 317, 0)
-
>>> class SmartTime(object):
-
... def DateAndTime(self, timeStrOrTup):
-
... if isinstance(timeStrOrTup, str):
-
... return timeStrOrTup
-
... if isinstance(timeStrOrTup, time.struct_time):
-
... return time.strftime("%a %b %d %H:%M:%S %Y", timeStrOrTup)
-
...
-
>>> st = SmartTime()
-
>>> st.DateAndTime(timeStr)
-
'Tue Nov 13 09:57:26 2007'
-
>>> st.DateAndTime(timeTup)
-
'Tue Nov 13 10:01:43 2007'
-
>>>
And using the "varargs" syntax (p 338 of Learning Python by Mark Lutz), it might look like this: -
>>> class SmartTime(object):
-
... def DateAndTime(self, *args):
-
... if isinstance(args[0], str):
-
... return args[0]
-
... if isinstance(args[0], time.struct_time):
-
... return time.strftime("%a %b %d %H:%M:%S %Y", args[0])
-
... return time.strftime("%a %b %d %H:%M:%S %Y", args)
-
...
-
>>> st = SmartTime()
-
>>> st.DateAndTime(2007, 11, 13, 10, 1, 43, 1, 317, 0)
-
'Tue Nov 13 10:01:43 2007'
-
>>> st.DateAndTime(timeStr)
-
'Tue Nov 13 09:57:26 2007'
-
>>> st.DateAndTime(timeTup)
-
'Tue Nov 13 10:01:43 2007'
-
>>>
| | Member | | Join Date: Sep 2007
Posts: 90
| | | re: implementing a calendar class
I only need the date like 11-11-2007, not the time. And this date is set by user, not accorded to the system time because if using the system time, it automatically recognizes the leap year, and there is no nextDate method is used
| | Member | | Join Date: Sep 2007
Posts: 90
| | | re: implementing a calendar class
The way I explained the problem might no be clear.
- The date (including month, day, and year for example Tues August 27, 2007) should be inputed by user.
- The class should have some methods to figure out what is the text input what is the numeric input, and be be to do the nextDate() which returns the next day of the year, this has to deal with the leap year.
Question: how can I write this?
| | Member | | Join Date: Nov 2007
Posts: 75
| | | re: implementing a calendar class
if you want to know next day:
import datetime
now = datetime.date(2003, 8, 6)
difference1 = datetime.timedelta(days=1)
difference2 = datetime.timedelta(weeks=-2)
print "One day in the future is:", now + difference1
print "Two weeks in the past is:", now + difference2
hope that helps a little, here's some more reading: http://pleac.sourceforge.net/pleac_python/datesandtimes.html
| | Member | | Join Date: Nov 2007
Posts: 75
| | | re: implementing a calendar class Quote:
Originally Posted by python101 The way I explained the problem might no be clear.
- The date (including month, day, and year for example Tues August 27, 2007) should be inputed by user.
- The class should have some methods to figure out what is the text input what is the numeric input, and be be to do the nextDate() which returns the next day of the year, this has to deal with the leap year.
Question: how can I write this? you are giving user an option to write month names in "text input"? usually if months are not in numerical format in application the user can choose the month from a list of months, not to write month name himself, or did I misunderstood this =)
| | Member | | Join Date: Nov 2007
Posts: 75
| | | re: implementing a calendar class
I'm just a noob, so sry if the code is not so nice looking
but what you think about this? =) -
import datetime
-
-
while 1: #loop while user has typed a proper date value
-
-
the_date = raw_input("Please give a date in DD.MM.YYYY format\n")
-
date_table = the_date.split('.') #splits "the_date" using . marks
-
#date_table[0] = DD , date_table[1] = MM, etc...
-
-
try: #checking if error happens when using datetime.date()
-
now = datetime.date(int(date_table[2]), int(date_table[1]), int(date_table[0])) #int() converts string to int
-
break #date value does exist, break from the while loop
-
-
except: #if there's error here it means that the date doesn't exist
-
print "You have type date in wrong format!, give day in (DD.MM.YYYY)\n"
-
-
-
next_day = datetime.timedelta(days=1)
-
-
print "next day is", now + next_day
-
ok, the printed next day is in totally different date format... (I'm lazy) but I think that it's easy to fix... :-D
| | Member | | Join Date: Sep 2007
Posts: 90
| | | re: implementing a calendar class
Thank you very much for helping me out.
Can I do this thing in the class? -
#assume I've already had CalculationDate class, when I run this class
-
>> CalculationDate(14,32,2004)
-
invalid date, please enter a gain 12/29/2004
-
|  | Member | | Join Date: Sep 2007
Posts: 52
| | | re: implementing a calendar class
To format the output, try something like this: - >>> import datetime
-
>>> months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
-
>>> dateA = datetime.date(2007, 5, 4)
-
>>> print "%s %d, %d" % (months[dateA.month-1], dateA.day, dateA.year)
-
May 4, 2007
|  | Member | | Join Date: Sep 2007
Posts: 52
| | | re: implementing a calendar class
Or this: - >>> dateA = datetime.date(2007, 5, 4)
-
>>> output = dateA.ctime().replace(" ", " ").split(" ")
-
>>> print "%s %s, %s" % (output[1], output[2], output[4])
-
May 4, 2007
|  | Member | | Join Date: Sep 2007
Posts: 52
| | | re: implementing a calendar class
Or even better: - >>> dateA.strftime("%B %d, %Y")
-
'May 14, 2007'
|  | Moderator | | Join Date: Oct 2006 Location: Nashville, TN
Posts: 1,563
| | | re: implementing a calendar class
Following is a class that does not use Python's datetime module: - import re
-
patt = "[/.]"
-
-
class Dates(object):
-
-
monthDict = dict(zip(range(1,13),['January', 'February', 'March', 'April', \
-
'May', 'June', 'July', 'August', 'September', \
-
'October', 'November', 'December']))
-
daysList1 = [31,28,31,30,31,30,31,31,30,31,30,31]
-
daysList2 = [31,29,31,30,31,30,31,31,30,31,30,31]
-
-
def __init__(self, dateStr):
-
# dateStr is in the format month/day/year (xx/xx/xxxx) or month.day.year
-
self.dateStr = dateStr
-
try:
-
self.month, self.day, self.year = [int(s) for s in re.split(patt, dateStr)]
-
except:
-
raise ValueError, "Invalid date format"
-
self.month_str = self.monthStr()
-
self.day_num = self.dayNo()
-
-
def isLeap(self, yr):
-
if not yr % 4:
-
return 1
-
return 0
-
-
def daysList(self, year):
-
return [self.daysList1, self.daysList2][self.isLeap(year)]
-
-
def monthStr(self):
-
# return the text representation of the month number
-
try:
-
return self.monthDict[self.month]
-
except KeyError:
-
raise ValueError, "Invalid month number"
-
-
def dayNo(self):
-
# return the day number in the year
-
if self.day < 1 or self.day > self.daysList(self.year)[self.month-1]:
-
raise ValueError, "Invalid day number"
-
return sum(self.daysList(self.year)[:self.month-1]) + self.day
-
-
def monthDayYr(self, day_num):
-
# return a tuple of month, day, year given a day number
-
# day number is with respect to the year of the instance
-
idx = 0
-
year = self.year
-
while day_num < 1:
-
day_num += sum(self.daysList(year))
-
year -= 1
-
while True:
-
if day_num <= self.daysList(year)[idx]:
-
return idx+1, day_num, year
-
day_num -= self.daysList(year)[idx]
-
idx += 1
-
if idx == 12:
-
idx = 0
-
year += 1
-
-
def nextDay(self):
-
return self+1
-
-
def preDay(self):
-
return self-1
-
-
def __add__(self, days):
-
return Dates('/'.join([str(item) for item in self.monthDayYr(self.dayNo() + days)]))
-
-
def __sub__(self, days):
-
return Dates('/'.join([str(item) for item in self.monthDayYr(self.dayNo() - days)]))
-
-
def __str__(self):
-
return "%s %d, %d" % (self.month_str, self.day, self.year)
|  | Moderator | | Join Date: Sep 2006 Location: Minden, Nevada, USA
Posts: 6,400
| | | re: implementing a calendar class
You guys do realize, don't you? All this and more is taken care of in the Calendar module.
|  | Moderator | | Join Date: Oct 2006 Location: Nashville, TN
Posts: 1,563
| | | re: implementing a calendar class Quote:
Originally Posted by bartonc You guys do realize, don't you? All this and more is taken care of in the Calendar module. Yes. Writing something myself is a lot more fun though.
| | Member | | Join Date: Sep 2007
Posts: 90
| | | re: implementing a calendar class Quote:
Originally Posted by bvdet Following is a class that does not use Python's datetime module: It is a little complicated and It seems that there is something I don't know. Like I never read something that when defining a method, we don't use self._something
assume that I have self._month, self._day, self._year has been property defined.
I have two list of maximum day for regular year and leap year.
I would like to write a nextDate() method to increase one day of current date, how can I write it? -
class CalculationDate:
-
daysList1 = [31,28,31,30,31,30,31,31,30,31,30,31]
-
daysList2 = [31,29,31,30,31,30,31,31,30,31,30,31]
-
def __ini__(m, d, yr):
-
self._month...
-
self._day...
-
self._year... # all of these things are written properly if user enters invalid information date, it will ask to change the date.
-
#now I would like to have a nextDay method:
-
def nextDay(self):
-
# how can I write this
-
|  | Moderator | | Join Date: Oct 2006 Location: Nashville, TN
Posts: 1,563
| | | re: implementing a calendar class Quote:
Originally Posted by python101 It is a little complicated and It seems that there is something I don't know. Like I never read something that when defining a method, we don't use self._something
assume that I have self._month, self._day, self._year has been property defined.
I have two list of maximum day for regular year and leap year.
I would like to write a nextDate() method to increase one day of current date, how can I write it? -
class CalculationDate:
-
daysList1 = [31,28,31,30,31,30,31,31,30,31,30,31]
-
daysList2 = [31,29,31,30,31,30,31,31,30,31,30,31]
-
def __ini__(m, d, yr):
-
self._month...
-
self._day...
-
self._year... # all of these things are written properly if user enters invalid information date, it will ask to change the date.
-
#now I would like to have a nextDay method:
-
def nextDay(self):
-
# how can I write this
-
The use of a leading underscore is for variables and methods intended to be non-public. I seldom make variables and methods non-public in the applications I have developed.
Did you notice that I included a nextDay() method in my post? The key is in the __add__(), monthDayYr(), and dayNo() methods. Method dayNo() returns the day number in the current year and does input validation on the day of the month. Method monthDayYr() returns a month, day, year tuple given a number of days with respect to the current year. Example: - >>> print a
-
June 8, 2007
-
>>> a.monthDayYr(a.dayNo())
-
(6, 8, 2007)
-
>>> a.monthDayYr(1)
-
(1, 1, 2007)
-
>>> a.monthDayYr(20000)
-
(10, 3, 2061)
-
>>> a.dayNo()
-
159
-
>>>
Method __add__() returns a Dates() object: - ....def __add__(self, days):
-
return Dates('/'.join([str(item) for item in self.monthDayYr(self.dayNo() + days)]))
The method nextDay() is now very simple: - ....def nextDay(self):
-
return self+1
- >>> print d
-
December 31, 2000
-
>>> d.nextDay()
-
<__main__.Dates object at 0x00DC70B0>
-
>>> print d.nextDay()
-
January 1, 2001
-
>>>
Following is an example using a Dates() object to parse the input and the Python datetime module: - if __name__ == '__main__':
-
import datetime
-
d = Dates('6/8/2007')
-
dt = datetime.datetime(d.year, d.month, d.day)
-
oneday = datetime.timedelta(days=1)
-
newdate = dt + oneday
-
print newdate
Output: >>> 2007-06-09 00:00:00
HTH
|  | | | | /bytes/about
We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights.
Get the best answers to your questions from over 226,295 network members.
|