Advertisement
Guest User

Age Regex

a guest
Jun 18th, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.68 KB | None | 0 0
  1. import re
  2.  
  3. datetime_re = re.compile("(?P<time>(?P<length>\d+)\s*(?P<unit>\w)\s*)")
  4.  
  5. ages = ['6W', '4M3W', '6Y', '1Y 3M', '16 Y 5M 2 W']
  6.  
  7. TIME_PER_YEAR = {
  8.     'Y': 1.0,
  9.     'W': 52.0,
  10.     'M': 12.0
  11. }
  12.  
  13.  
  14. def age_to_years(length, unit_time):
  15.     try:
  16.         length = int(length)
  17.     except ValueError:
  18.         pass
  19.     return length / TIME_PER_YEAR[unit_time.upper()]
  20.  
  21.  
  22. if __name__ == '__main__':
  23.     for time_input in ages:
  24.         print(time_input)
  25.         for datetime_out in datetime_re.finditer(time_input):
  26.             print(datetime_out.groups())
  27.         print(sum(age_to_years(*datetime_out.groups()[1:]) for datetime_out in datetime_re.finditer(time_input)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement