diff of two given dates

Problem 
#!/usr/bin/env python


import math, time

#return value:
# 0 : apart excatly one month
# -1 : less than one month
# 1 : more than one month

def difftime(t1, t2):

t1 = time.strptime(t1, "%b %d %Y")
t2 = time.strptime(t2, "%b %d %Y")

y = math.fabs(t1.tm_year - t2.tm_year)
m = math.fabs(t1.tm_mon - t2.tm_mon)

if y == 1:
if m == 11:
if t1.tm_mday == t2.tm_mday:

return 0

elif (t1.tm_mon < t2.tm_mon and t1.tm_mday < t2.tm_mday) or (t2.tm_mon < t1.tm_mon and t2.tm_mday < t1.tm_mday):

return -1

elif y == 0:

if m == 1:

if t1.tm_mday == t2.tm_mday:

return 0

elif (t1.tm_mon < t2.tm_mon and t1.tm_mday > t2.tm_mday) or (t2.tm_mon < t1.tm_mon and t2.tm_mday > t1.tm_mday):

return -1

elif m == 0:

return -1

return 1


try:
t1 = raw_input("date 1:")
t2 = raw_input("date 2:")

out = {-1:"less than one month", 0: "exactly one month", 1:"more than one month"}

r = difftime(t1, t2)

print 'Given dates apart ', out[r]
except:
print "Invalid dates"
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s