Home > database >  How to simplify a date rule
How to simplify a date rule

Time:09-06

I have a date rule that handles dates between certain dates with different outcomes. I was wondering if there is a way to simplify/combine the rules?

date = "YYYY-MM-DD"
rule1_1993_start = "1993-02-01" #sets date to "2000-01-01"
rule1_1993_end = "1993-05-31"
rule1_1994_start = "1994-02-01"
rule1_1994_end = "1994-05-31"
rule2_1993_start = "1993-06-01" #keeps the same date
rule2_1993_end = "1993-12-01"
rule2_1994_start = "1994-06-01"
rule2_1994_end = "1994-12-01"
rule3_1993_start = "1993-01-01" #sets date to "1995-MM-DD"
rule3_1993_end = "1993-01-31"
rule3_1994_start = "1994-01-01"
rule3_1994_end = "1994-01-31"

if rule1_1993_start <= date <= rule1_1993_end: #date="1993-03-04"
      date = "2000-01-01"
if rule2_1993_start <= date <= rule1_1993_end: #date="1993-07-01"
      date = "1993-07-01"
if rule3_1993_start <= date <= rule1_1993_end: #date="1993-01-12"
      date = "1995-01-12"

CodePudding user response:

Processing dates can be a little tricky; there tend to be lots of corner cases. If you need a more production-quality function, I recommend you use Python's time module:

import time
def convert_date(date):                                                         
    return time.strptime(date, '%Y-%m-%d')

When your dates are in this format, you can use math operators (<, <=, etc) to do comparisons. You can also compare based on month and year, so for example your third rule becomes something like:

# If date in January 1993 or 1994
if((date.tm_year == 1993 || date.tm_year == 1994) && date.tm_mon == 1):
  ...

You can convert dates back to strings using Python's strftime routine:

def date_to_string(date):
  return time.strftime('%Y-%m-%d', date)

strptime docs: https://docs.python.org/3/library/time.html#time.strftime

strftime docs: https://docs.python.org/3/library/time.html#time.strptime

  • Related