Readable Time Format (w/ Good Grammar!) - python

I've been reading posts upon posts of the methods for converting an input number of seconds, which should be output as a formal string with given durations (hours, minutes, seconds). But I want to know how to format it so that it accounts for singularization/pluralization, when I know, for example, 62 seconds should read as "1 minute and 2 seconds" as opposed to 120 seconds which is simply "2 minutes".
One other criteria is that it should return "now" if the seconds is 0.
Here's my code so far:
def format_duration(seconds, granularity = 2):
intervals = (('hours', 3600), ('minutes', 60), ('seconds', 1))
human_time = []
for name, count in intervals:
value = seconds // count
if value:
seconds -= value * count
if value == 1:
name = name.rstrip('s')
human_time.append("{} {}".format(value, name))
else:
return "now"
return ','.join(human_time[:granularity])
Please help! Thanks!
MJ

Your code already works quite nicely, you just have one problem with your return "now" that I fixed in the code below. What else do you want your code to do?
def prettyList(human_time):
if len(human_time) > 1:
return ' '.join([', '.join(human_time[:-1]), "and", human_time[-1]])
elif len(human_time) == 1:
return human_time[0]
else:
return ""
def format_duration(seconds, granularity = 2):
intervals = (('hours', 3600), ('minutes', 60), ('seconds', 1))
human_time = []
for name, count in intervals:
value = seconds // count
if value:
seconds -= value * count
if value == 1:
name = name.rstrip('s')
human_time.append("{} {}".format(value, name))
if not human_time:
return "now"
human_time = human_time[:granularity]
return prettyList(human_time)
Edit: so I added a function to prettify the output, the last terms in the list will be separed by a "and" and all the others before by a comma. This will still work even if you add more intervals in your code (like ('days', 86400)). The output now looks like 2 hours, 1 minute and 43 seconds or 25 minutes and 14 seconds.

Made some tweaks for readability :
def pretty_list(human_time):
return human_time[0] if len(human_time) == 1 else ' '.join([', '.join(human_time[:-1]), "and", human_time[-1]])
def get_intervals(seconds):
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
return (
("hour", h),
("minute", m),
("second", s)
)
def format_duration(seconds, granularity=3):
intervals = get_intervals(seconds)
human_time = []
for name, value in intervals:
if value == 0:
continue
elif value == 1:
human_time.append("{} {}".format(value, name))
else:
human_time.append("{} {}s".format(value, name))
return (pretty_list(human_time[:granularity])) if len(human_time) != 0 else "now"

You can try to code for each variation:
def timestamp(ctime):
sec = int(ctime)
if sec == 0:
return "Now"
m, s = divmod(sec, 60)
h, m = divmod(m, 60)
if h == 1: hr_t = 'Hour'
else: hr_t = 'Hours'
if m == 1: mn_t = 'Minute'
else: mn_t = 'Minutes'
if s == 1: sc_t = 'Second'
else: sc_t = 'Seconds'
time_stamp = ""
if h > 0 and m ==0 and s ==0:
time_stamp = "%02d %s " % (h, hr_t)
elif h > 0:
time_stamp = "%02d %s, " % (h, hr_t)
if m > 0 and s !=0:
time_stamp = time_stamp +"%02d %s and %02d %s" % (m, mn_t, s, sc_t)
elif m > 0 and s == 0:
time_stamp = time_stamp +"%02d %s" % (m, mn_t)
elif m == 0 and s != 0:
time_stamp = time_stamp +"%02d %s" % (s, sc_t)
return time_stamp
print (timestamp(11024))
print (timestamp(0))
print (timestamp(31))
print (timestamp(102))
print (timestamp(61))
print (timestamp(60))
print (timestamp(3600))
print (timestamp(3632))
03 Hours, 03 Minutes and 44 Seconds
Now
31 Seconds
01 Minute and 42 Seconds
01 Minute and 01 Second
01 Minute
01 Hour
01 Hour, 32 Seconds
Or you can use the relativedelta option in dateutil and then pick the bones out of it.
from dateutil.relativedelta import relativedelta
attrs = ['years', 'months', 'days', 'hours', 'minutes', 'seconds']
human_readable = lambda delta: ['%d %s ' % (getattr(delta, attr), getattr(delta, attr) != 1 and attr or attr[:-1]) for attr in attrs if getattr(delta, attr) or attr == attrs[-1]]
readable=''
for i in human_readable(relativedelta(seconds=1113600)):
readable += i
print readable
print human_readable(relativedelta(seconds=13600))
print human_readable(relativedelta(seconds=36))
print human_readable(relativedelta(seconds=60))
print human_readable(relativedelta(seconds=3600))
12 days 21 hours 20 minutes 0 seconds
['3 hours ', '46 minutes ', '40 seconds ']
['36 seconds ']
['1 minute ', '0 seconds ']
['1 hour ', '0 seconds ']
For more examples of the second example see: http://code.activestate.com/recipes/578113-human-readable-format-for-a-given-time-delta/
which is where I stole almost all the second set of code from

I found it! I actually needed more intervals - the durations asked for were lengthier than I thought...
def prettyList(human_time):
if len(human_time) > 1:
return ' '.join([', '.join(human_time[:-1]), "and", human_time[-1]])
elif len(human_time) == 1:
return human_time[0]
else:
return ""
def format_duration(seconds, granularity = 4):
intervals = (('years', 29030400), ('months', 2419200), ('weeks', 604800),('days', 86400),('hours', 3600), ('minutes', 60), ('seconds', 1))
human_time = []
for name, count in intervals:
value = seconds // count
if value:
seconds -= value * count
if value == 1:
name = name.rstrip('s')
human_time.append("{} {}".format(value, name))
if not human_time:
return "now"
human_time = human_time[:granularity]
return prettyList(human_time)

I think that I have covered all of the bases here but I'm sure someone will let me know if I have made an error (large or small) :)
from dateutil.relativedelta import relativedelta
def convertdate(secs):
raw_date = relativedelta(seconds=secs)
years, days = divmod(raw_date.days, 365) # To crudely cater for leap years / 365.2425
hours = raw_date.hours
minutes = raw_date.minutes
seconds = raw_date.seconds
full = [years,days,hours,minutes,seconds]
date_text=['','','','','']
if years == 1: date_text[0] = "Year"
else: date_text[0] = "Years"
if days == 1: date_text[1] = "Day"
else: date_text[1] = "Days"
if hours == 1: date_text[2] = "Hour"
else: date_text[2] = "Hours"
if minutes == 1: date_text[3] = "Minute"
else: date_text[3] = "Minutes"
if seconds == 1: date_text[4] = "Second"
else: date_text[4] = "Seconds"
first_pos = 0
final_pos = 0
element_count = 0
# Find the first and final set positions and the number of returned values
for i in range(5):
if full[i] != 0:
final_pos = i
element_count +=1
if first_pos == 0:
first_pos = i
# Return "now" and any single value
if element_count == 0:
return "Now"
if element_count == 1:
return "%02d %s" % (full[final_pos],date_text[final_pos])
# Initially define the separators
separators=['','','','','']
ret_str=''
for i in range(4):
if full[i] != 0:
separators[i] = ', '
separators[final_pos] = ''
# Redefine the final separator
for i in range(4,-1,-1):
if separators[i] == ', ':
separators[i] = ' and '
break
#Build the readable formatted time string
for i in range(5):
if full[i] != 0:
ret_str += "%02d %s%s" % (full[i],date_text[i],separators[i])
return ret_str
print convertdate(1111113601)
print convertdate(1111113635)
print convertdate(1111113600)
print convertdate(1111111200)
print convertdate(1111104000)
print convertdate(1111104005)
print convertdate(11113240)
print convertdate(11059240)
print convertdate(11113600)
print convertdate(36)
print convertdate(60)
print convertdate(61)
print convertdate(121)
print convertdate(122)
print convertdate(120)
print convertdate(3600)
print convertdate(3601)
35 Years, 85 Days, 02 Hours, 40 Minutes and 01 Second
35 Years, 85 Days, 02 Hours, 40 Minutes and 35 Seconds
35 Years, 85 Days, 02 Hours and 40 Minutes
35 Years, 85 Days and 02 Hours
35 Years and 85 Days
35 Years, 85 Days and 05 Seconds
128 Days, 15 Hours and 40 Seconds
128 Days and 40 Seconds
128 Days, 15 Hours, 06 Minutes and 40 Seconds
36 Seconds
01 Minute
01 Minute and 01 Second
02 Minutes and 01 Second
02 Minutes and 02 Seconds
02 Minutes
01 Hour
01 Hour and 01 Second

Related

count the number of days between two dates

I am counting number of days between two dates.For first testcase output is wrong 10108
expected output 10109
In first test case 1 day is missing in output
from typing import*
class Solution:
def daysBetweenDates(self, date1: str, date2: str) -> int:
d1 = self.days(int(date1[:4]),int(date1[5:7]),int(date1[8:]))
d2 = self.days(int(date2[:4]),int(date2[5:7]),int(date2[8:]))
return abs(d2-d1)
def isLeap (self, N):
if N % 400 == 0:
return True
if N % 100 == 0:
return False
if N % 4 != 0:
return False
return True
def days(self, year,month,rem_days):
months_list = [31,28,31,30,31,30,31,31,30,31,30,31]
days_count = 0
for i in range(1971,2101):
if year > i:
if self.isLeap(i):
days_count += 366
else:
days_count += 365
else:
break
if self.isLeap(year) and month > 2:
days_count += 1
for j in range(1,month):
if month > j:
days_count += months_list[j]
return days_count + rem_days
vals = Solution()
print(vals.daysBetweenDates("2010-09-12","1983-01-08"))
print(vals.daysBetweenDates("2019-06-29", "2019-06-30"))
print(vals.daysBetweenDates("2020-01-15", "2019-12-31"))
The month starts at one, you get the number of days for each month from the wrong index (1 for January when the correct index is 0...). Subtract one when you look up the days for each month
for j in range(1, month):
days_count += months_list[j - 1]

How to code a function that converts label to seconds?

def seconds_to_label_converter(seconds):
hours = divmod(seconds,3600)[0]
minutes = divmod(seconds-(hours*3600),60)[0]
remaining_seconds = seconds-((hours*3600)+(minutes*60))
if remaining_seconds == 0 and hours == 0 and minutes == 0:
time_label = "No info"
elif hours > 1:
time_label = f"{hours} Hours {minutes} Minutes {remaining_seconds} Seconds"
elif hours == 1:
time_label = f"{hours} Hour {minutes} Minutes {remaining_seconds} Seconds"
elif hours == 0 and minutes > 1:
time_label = f"{minutes} Minutes {remaining_seconds} Seconds"
elif hours == 0 and minutes == 1:
time_label = f"{minutes} Minute {remaining_seconds} Seconds"
elif hours == 0 and minutes == 0:
time_label = f"{remaining_seconds} Seconds"
print(time_label)
seconds_to_label_converter(21254)
I have a "seconds to label converter" like this. Now I need a function that will do the opposite. But I don't know how to do it.
for example:
label_to_seconds_converter("5 Hours 54 Minutes 14 Seconds")
# >>> OUTPUT = 21254
Try this. Extract specific strings using re and then extract numbers
import re
def seconds_to_label_converter(seconds):
x=re.findall(r'\b\d+\s*hour[s]?\b',seconds.lower())
y=re.findall(r'\b\d+\s*minute[s]?\b',seconds.lower())
z=re.findall(r'\b\d+\s*second[s]?\b',seconds.lower())
secs=0
if x:
for i in re.findall(r'\d+',''.join(x)):
secs +=3600*int(i)
if y:
for i in re.findall(r'\d+',''.join(y)):
secs +=60*int(i)
if z:
for i in re.findall(r'\d+',''.join(z)):
secs +=int(i)
return secs
print(seconds_to_label_converter('4 hours 50 seconds'))
Returns
14450
print(seconds_to_label_converter('4 hours 10 minutes 50 seconds'))
returns
15050
print(seconds_to_label_converter('5 Hours 54 Minutes 14 Seconds'))
Returns
21254
You could do something like this:
def text_to_second(txt: str):
items = [int(x) if x.isnumeric() else x for x in txt.split() ]
seconds = 0
for i in range(0,len(items),2):
a = items[i+1]
if a.lower()=="hours" or a.lower()=="hour":
seconds += 3600*items[i]
elif a.lower()=="minutes" or a.lower()=="minute":
seconds += 60*items[i]
elif a.lower()=="seconds" or a.lower()=="second":
seconds += items[i]
return seconds
print(text_to_second("5 Hours 54 Minutes 14 Seconds"))
#output: 21254
Another option would be to use the zip function:
def label_to_seconds_converter(label: str) -> int:
label_list = label.split()
seconds = 0
for amount, word in zip(label_list[::2], label_list[1::2]):
if "hour" in word.lower():
seconds += int(amount) * 3600
elif "minute" in word.lower():
seconds += int(amount) * 60
else:
seconds += int(amount)
return seconds
print(label_to_seconds_converter("5 Hours 54 Minutes 14 Seconds"))
result
21254
try this :
def label_to_seconds(label):
times = re.findall(r'\b\d+\s*[hours|minutes|seconds]?\b', label.lower())
list_len = len(times)
if list_len == 3:
return int(times[0].strip()) * 3600 + int(times[0].strip()) * 60 + int(times[0].strip())
if list_len == 2:
return int(times[0].strip()) * 60 + int(times[1].strip())
if list_len == 1:
return int(times[0].strip())
else:
print('Invalid Format')

Cannot operate on year value of regular expression

This is my first question here so please forgive and educate on any formatting errors. I am new to Python and going through automate the boring stuff. Decided to expand the date detection project by using the clipboard and formatting some things also. The problem I have is in any operation taken on the year part of the REGEX.
I have commented out my last attempt to validate the year and gave up and changed the REGEX to only find dates from 1000 to 2999 and skipped code validation of the dates.
I now need to validate leap years but I'm back to having to work with the year variable, but once again no operation has any effect.
Basically the problem is I can extract the year value and display it but I cannot modify it or do checks against it.
#! python3
#! detect dates in a block of text
import pyperclip
import re
#!import numpy as np
text = str(pyperclip.paste())
def datedetection(text):
dateRegex = re.compile(
r"""(
(\d|\d\d) #! match day
(/{1}) #! match /
(\d|\d\d) #! match month
(/{1}) #! match /
([1|2][0-9][0-9][0-9]) #! match year
)""",
re.VERBOSE,
)
matches = []
for groups in dateRegex.findall(text):
day = str(groups[1])
slash1 = str(groups[2])
month = str(groups[3])
slash2 = str(groups[4])
year = str(groups[5])
month_range_30 = ["04", "06", "09", "11"]
month_range_31 = ["01", "03", "05", "07", "08", "10", "12"]
month_range_Feb = ["02"]
#!year_range = np.arange(1000, 3000, 1).tolist()
if len(day) == 1:
day = "0" + day
else:
day = day
if len(month) == 1:
month = "0" + month
else:
month = month
if month in month_range_31:
if int(day) > 31:
day = "Too many days in a month with only 31 days."
slash1 = month = slash2 = year = ""
elif month in month_range_30:
if int(day) > 30:
day = "Too many days in a month with only 30 days."
slash1 = month = slash2 = year = ""
elif month in month_range_Feb:
if int(day) > 29:
day = "Too many days in February."
slash1 = month = slash2 = year = ""
elif int(month) > 12:
day = "Found an invalid month."
slash1 = month = slash2 = year = ""
elif month in month_range_Feb:
if (
int(day) == 29
and (int(year) % 4 == 0)
and (int(year) % 400 == 0)
and (int(year) % 100 == 0)
):
day = day
elif month in month_range_Feb:
if (
int(day) == 29
and (int(year) % 4 == 0)
and (int(year) % 100 != 0)
):
day = "Found an invalid leap year."
slash1 = month = slash2 = year = ""
#!elif year not in year_range:
#!day = "Year is out of range."
#!slash1 = month = slash2 = year = ""
dates = "".join([day, slash1, month, slash2, year])
matches.append(dates)
if len(matches) > 0:
pyperclip.copy("\n".join(matches))
print("Copied to clipboard:")
print("\n".join(matches))
else:
print("No dates found.")
datedetection(text)
In my approach to this project, I considered validating the days, months, and year ranges as part of the regular expression. I then defined functions to check for the leap year, and validate the number of days according to the months.
I found that way simpler and easier to understand and follow. As below:
dateRegex = re.compile(r'([0-3][0-9])/([0-1][0-9])/([1-2][0-9]{3})')
def is_leap_year(year):
year = int(year)
if year % 4 == 0:
if year % 100 == 0:
return year % 400 == 0
else:
return True
else:
return False
def is_valid_date(day, month, year):
if month == '02':
if is_leap_year(year):
return int(day) <= 29
else:
return int(day) <= 28
elif month in ['04', '06', '09', '11']:
return int(day) <= 30
else:
return int(day) <= 31
You can find the rest of my code below.
https://gist.github.com/alialbusaidi/f56e4c9342f622434f8bff0549f94884
The problem was the operations before the year operations. The day and month operations were overwriting the year values. Not entirely sure how or why at this point, but moving the year code above the day and month code has started to fix the issue.

How to put numbers in a time format if conversions are already completed?

I am trying to take a string and convert into 24 hour time. For example, if I am given the string "07:05:45PM", it should return "19:05:45". I have completed all the necessary conversions, I am just not sure how I am supposed to put them all together and have it so that if there were only 5 minutes or 5 seconds, it would place a zero like "xx:05:06".
def timeConversion(s):
nums = s[:8]
hh,mm,ss = [v for v in nums.split(":")]
time = s[8:]
if time == 'AM':
return nums
else:
total = (int(hh) * 3600 + int(mm) * 60 + int(ss)) + 43200
if s == "12:00:00PM":
return nums
hh = total // 3600
mm = total // 60 % 60
ss = total % 60
print(timeConversion("07:05:45PM"))
Only the hours and suffix have any significance in your output. The key is that 12AM is 00, and 12PM is 12. 12:00 is not the only time that deserves this treatment: 12:01 does too. Use the modulo operator to avoid any special cases at all:
def time_conversion(s):
hh = int(s[:2]) % 12 # this is the magical part 12->0
mmss = s[2:8]
suffix = s[8:].strip().upper()
if suffix == 'PM':
hh += 12
return f'{hh:02d}{mmss}'
Here is the working code. For the input "07:05:45PM", it returns "19:05:45". You just need to add a '0' if the minutes or seconds values are less than 10.
def timeConversion(s):
nums = s[:8]
hh,mm,ss = [v for v in nums.split(":")]
time = s[8:]
if time == 'AM':
return nums
else:
total = (int(hh) * 3600+int(mm)*60+int(ss))+43200
if s == "12:00:00PM":
return nums
hh = str(total//3600)
mm = total//60 % 60
ss = total % 60
mm_str = '0'+ str(mm) if mm <= 9 else str(mm)
ss_str = '0'+ str(ss) if ss <= 9 else str(ss)
time_str = str(hh) + ':' + mm_str + ":" + ss_str
return time_str
print(timeConversion("07:05:45PM"))
Since you are dealing with a string, perhaps most of the code could deal with the string.
EDIT: Revised code as per Mad Physicist's comments
def convert(s):
if s[8:] == 'AM':
if s[:2] == '12':
return '00' + s[2:8]
else:
return s[:8]
elif s[8:] == 'PM':
if s[:2] == '12':
return s[:8]
else:
return str(int(s[:2])+ 12) + s[2:8]
for t in ['12:00:00AM', '01:01:01AM', '12:01:01PM', '01:10:11PM', '11:20:20PM']:
print(t, convert(t))
Prints:
12:00:00AM 00:00:00
01:01:01AM 01:01:01
12:01:01PM 12:01:01
01:10:11PM 13:10:11
11:20:20PM 23:20:20

Fetch and validate date by reading char by char in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How do I read a date in MM-DD-YY format and validate as a real date?
I know it would be easier and more robust to handle it with the datetime module - but that's not what I want, so any solutions around using the the following code is appreciated:
dataType = MM-DD-YY
actualResult = 12-31-13
rIndex: counter variable for actualResult
rLen: length of actualResult
def compareDate (dataType, actualResult, rIndex, rLen):
dateString = ""
bhCount , result , count = 0 , 0 , 0
while (rIndex < rLen):
ch = actualResult[rIndex]
print ("Char %c" % ch)
dateString += str(ch)
if(ch >='0' and ch <= '9'):
count += 1
if(count == 2):
count = 0
bHyphen = False
elif(count > 2):
result = -1
break
elif(ch == "-"):
bhCount += 1
if((count == 0) and (bHyphen == False)):
bHyphen = True
else:
break
else:
break
rIndex += 1
#print dateString
return (result, rIndex)
What I am doing wrong? Any help will be appreciated.
class ValidationError(BaseException):
pass
class MyDate(object):
mounth = int()
day = int()
year = int()
_correct_mounth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def validate(self, day, mounth, year):
if not 1 <= mounth <= 12:
raise ValidationError, 'Invalid mounth!'
if year < 1:
raise ValidationError, 'Invalid year!'
if mounth == 2 and not year % 4:
if not 1 <= day <= 29:
raise ValidationError, 'Invalid day!'
else:
if not 1 <= day <= self._correct_mounth[mounth-1]:
raise ValidationError, 'Invalid day!'
return True
def __init__(self, date):
if not isinstance(date, basestring):
raise ValidationError, 'Not a string!'
date_parts = date.split('-')
if not isinstance(date_parts, list) or not len(date_parts) == 3:
raise ValidationError, 'Can`t change to list with 3 elements!'
for i in date_parts:
try:
int(i)
except TypeError:
raise ValidationError, 'Cannot convert to int!'
mounth = int(date_parts[0])
day = int(date_parts[1])
year = int(date_parts[2])
if self.validate(day, mounth, year):
self.mounth, self.day, self.year = mounth, day, year
dates = '12-31-13|08-23-12|10-10-13'
unchecked_dates = dates.split('|')
checked_dates = list()
for d in unchecked_dates:
try:
new_date = MyDate(d)
except ValidationError, e:
print '{0} is invalid date! {1}'.format(d, e)
else:
checked_dates.append(new_date)
if len(unchecked_dates) == len(checked_dates):
print 'All dates are correct.'
else:
print 'Correct dates: {0}'.format(checked_dates)
ANSWER
def compareDate (dataType, actualResult, rIndex, rLen):
hyphenCount , result , count = 0 , 0 , 0
dateString = ""
while (rIndex < rLen):
ch = actualResult[rIndex]
if (ch == '.'):
break
if(ch >= '0' and ch <= '9'):
hyphenCount = 0
count += 1
if(count > 2):
result = -1
print " d = "
break;
dateString += str(ch)
if(ch == '-'):
count = 0
hyphenCount += 1
if(hyphenCount > 1):
print " h = "
result = -1
break
#print ("Char %c" % ch)
rIndex += 1
print "dateString is = %s" % dateString
if result != -1:
msg = ""
mt = dateString[0] + dateString[1]
dt = dateString[2] + dateString[3]
yr = dateString[4] + dateString[5]
leap = '20'+yr
print mt, dt, yr
mt = int(mt)
dt = int(dt)
yr = int (yr)
leap = int(yr)
#create and call function which verify date
result,msg = verifyDate(mt,dt,yr,leap)
print msg
return (result, rIndex)
def verifyDate(mt,dt,yr,leap):
res = 0
msg = ""
leapyr = checkForLeapYear(leap)
if(yr >= 00 and yr <= 99):
if(leapyr): # for leap year
if(mt == 2):
if(dt >= 01 and dt <= 29):
res = 0
else:
msg = "should not exceed 29"
elif(mt == 1 or mt == 3 or mt == 5 or mt == 7 or mt == 8 or mt == 10 or mt == 12):
if(dt >= 01 and dt <= 31):
res = 0
else:
msg = "should not exceed 31"
res = -1
elif(mt == 4 or mt == 6 or mt == 9 or mt == 11):
if(dt >= 01 and dt <= 30):
res = 0
else:
msg = "should not exceed 30"
res = -1
else:
msg = "month should in btwn 01 to 12"
res = -1
# for leap year ...Ends Here
else:
if((mt >= 1) and (mt <= 12)):
if(mt == 2):
if(dt >= 01 and dt <= 28):
res = 0
else:
msg = "should not exceed 28"
res = -1
elif(mt == 1 or mt == 3 or mt == 5 or mt == 7 or mt == 8 or mt == 10 or mt == 12):
if(dt >= 01 and dt <= 31):
res = 0
else:
msg = "should not exceed 31"
res = -1
elif(mt == 4 or mt == 6 or mt == 9 or mt == 11):
if(dt >= 01 and dt <= 30):
res = 0
else:
msg = "should not exceed 30"
res = -1
else:
msg = "month should in btwn 01 to 12"
res = -1
else:
msg = "year should in btwn 00 to 99"
res = -1
return (res,msg)
def checkForLeapYear(yr):
if((yr %100) == 0 and (yr % 400 == 0 )):
return True
elif(yr%4 == 0):
return True
else:
return False
What else i can do with code to improve complexity and reduce lines of code.
Please answer with examples..

Categories