在Python 3.8中,我如何解析字符串以提取日期并在适当的情况下将2021指定为年份



我使用日期解析器来解析字符串,并返回一个日期值以与提取日期进行比较,然后返回一个整数值作为两者之间的差值。在某些情况下,解析的日期是一个范围,在这种情况下,我对范围的两端求平均值,并得到平均值和提取日期之间的差。

当这个月进入明年时,我很难将年份替换为2021年,所以我的差异都是负面的如何将年份替换为2021

输出示例:

extraction date:  10/26/2020 0:00;   promo_message: ["Arrives: Feb 26 - March 2"] ;                   first_delivery:   -243  ;     last_delivery:  -238   ;   delivery:   -240

代码:

elif 'Arrives' in row[6] and '-' in row[6]:
try:
example_2 = promo_message.split('-',1)
first_delivery = (parse(example_2[0], fuzzy=True))
if first_delivery.month == 1:
first_delivery = first_delivery.replace(month=1, year=2021, tzinfo=None)
elif first_delivery.month == 2:
first_delivery = first_delivery.replace(month=2, year=2021, tzinfo=None)
elif first_delivery.month == 3:
first_delivery = first_delivery.replace(month=3, year=2021, tzinfo=None)
first_delivery = (parse(example_2[0], fuzzy=True))
first_delivery_int = (first_delivery - extraction_date).days
second_delivery = (parse(example_2[1], fuzzy=True))
if second_delivery.month == 1:
second_delivery = second_delivery.replace(month=1, year=2021)
elif second_delivery.month == 2:
second_delivery = second_delivery.replace(month=2, year=2021)
elif second_delivery.month == 3:
second_delivery = second_delivery.replace(month=3, year=2021)

second_delivery = (parse(example_2[1], fuzzy=True))
second_delivery_int = (second_delivery - extraction_date).days

你为什么要进行某种形式的陪审团操纵日期?如果您正在以某种已知的格式获取日期,那么请解析该格式并创建日期时间对象。一旦有了datetime对象,基于其中的方法进行日期操作就很简单了。

使用replace(year=2021)是正确的想法,但如果使用extraction_date来更改年份,则可能会更容易。然后你可以做这样的事情:

from dateutil.parser import parse
def average_diff(extraction_date, promo_msg):
split_date = promo_msg.split("-", 1)
first_delivery = parse(split_date[0], fuzzy=True)
second_delivery = parse(split_date[1], fuzzy=True)
# Check for year rollover
if first_delivery < extraction_date:
first_delivery = first_delivery.replace(year=extraction_date.year + 1)
second_delivery = second_delivery.replace(year=extraction_date.year + 1)
diff1 = (first_delivery - extraction_date).days
diff2 = (second_delivery - extraction_date).days

# Deal with integer days, so use integer division
return (diff1 + diff2) // 2

这里有一个关键假设,即extraction_date也是datetime对象(而不是date对象(。如果它也是dateutil.parserparse函数的结果,那么你应该没事。现在,这个代码不依赖于所讨论的年份、月份甚至日期。

相关内容

  • 没有找到相关文章

最新更新