如何简化日期规则



我有一个日期规则,用于处理具有不同结果的特定日期之间的日期。我想知道是否有一种方法可以简化/组合规则?

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"

处理日期可能有点棘手;往往会有很多角落案例。如果您需要更高生产质量的函数,我建议您使用Python的time模块:

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

当您的日期为这种格式时,您可以使用数学运算符(<、<=等(进行比较。你也可以根据月份和年份进行比较,所以例如,你的第三条规则变成了这样:

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

您可以使用Python的strftime例程将日期转换回字符串:

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

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

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

最新更新