Advertisement
acclivity

Compute time between 2 dates

Nov 14th, 2020
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.03 KB | None | 0 0
  1. # Calculate the number of days between two dates entered from keyboard
  2. from datetime import date
  3.  
  4. def getdate(stra):
  5.     while True:
  6.         s1 = input("Enter " + stra + " date as yyyy-mm-dd: ")
  7.         ymd = makedate(s1)      # validate the input string, and make a date tuple
  8.         if ymd:
  9.             return ymd
  10.         print("Invalid format, try again")
  11.  
  12. def makedate(inp):
  13.     splitd = inp.split('-')     # Split string on hyphens  
  14.     if len(splitd) != 3:                # there should be 3 sections
  15.         return None
  16.     # check each section is numeric (more validation could be done here!!)
  17.     if splitd[0].isdigit() and splitd[1].isdigit() and splitd[2].isdigit():
  18.     # extract the year, month, and day
  19.         y = int(splitd[0])
  20.         m = int(splitd[1])
  21.         d = int(splitd[2])
  22.         return y,m,d
  23.     return None
  24.  
  25. s1 = getdate("first")
  26. s2 = getdate("second")
  27. res1 = makedate(s1)
  28. res2 = makedate(s2)
  29.  
  30. d1 = date(res1[0], res1[1], res1[2])
  31. d2 = date(res2[0], res2[1], res2[2])
  32. delta = d2 - d1
  33. print(delta.days)
  34.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement