Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#23050 Handle different expiration date format #1571

Merged
merged 6 commits into from
Sep 9, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion api/namex/VERSION.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = '1.2.4'
__version__ = '1.2.5'
42 changes: 19 additions & 23 deletions api/namex/resources/requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@
from namex.utils.auth import cors_preflight
from namex.analytics import SolrQueries, RestrictedWords, VALID_ANALYSIS as ANALYTICS_VALID_ANALYSIS
from namex.utils import queue_util
from .utils import DateUtils


setup_logging() # Important to do this first

Expand Down Expand Up @@ -742,33 +744,27 @@
existing_nr.save_to_db()

if json_input.get('consent_dt', None):
json_input['consent_dt'] = str(datetime.strptime(
str(json_input['consent_dt'][5:]), '%d %b %Y %H:%M:%S %Z'))
consentDate = json_input['consent_dt']
json_input['consent_dt'] = DateUtils.parse_date_string(consentDate, '%d %b %Y %H:%M:%S %Z')

# convert Submitted Date to correct format
if json_input.get('submittedDate', None):
json_input['submittedDate'] = str(datetime.strptime(
str(json_input['submittedDate'][5:]), '%d %b %Y %H:%M:%S %Z'))
submittedDateStr = json_input['submittedDate']
json_input['submittedDate'] = DateUtils.parse_date_string(submittedDateStr, '%d %b %Y %H:%M:%S %Z')

# convert Expiration Date to correct format
if json_input.get('expirationDate', None):
expiration_str = json_input['expirationDate']

# Convert the date (either UTC or ISO) into a UTC datetime object
if expiration_str.endswith('UTC'):
parsed_date = datetime.strptime(expiration_str[5:], '%d %b %Y %H:%M:%S %Z')
parsed_date = parsed_date.replace(tzinfo=UTC)
else:
parsed_date = datetime.fromisoformat(expiration_str)
if parsed_date.tzinfo is None:
parsed_date = parsed_date.replace(tzinfo=UTC) # If it's naive, assume UTC
else:
parsed_date = parsed_date.astimezone(UTC) # Convert any timezone-aware datetime to UTC

# Convert the UTC datetime object to the end of day in pacific time without milliseconds
pacific_time = parsed_date.astimezone(timezone('US/Pacific'))
end_of_day_pacific = pacific_time.replace(hour=23, minute=59, second=0, microsecond=0)
json_input['expirationDate'] = end_of_day_pacific.strftime('%Y-%m-%d %H:%M:%S%z')
current_app.logger.debug(f"Parsing expirationDate: {json_input['expirationDate']}")
Dismissed Show dismissed Hide dismissed
try:
expirationDateStr = json_input['expirationDate']
expirationDate = DateUtils.parse_date(expirationDateStr)
# Convert the UTC datetime object to the end of day in pacific time without milliseconds
pacific_time = expirationDate.astimezone(timezone('US/Pacific'))
end_of_day_pacific = pacific_time.replace(hour=23, minute=59, second=0, microsecond=0)
json_input['expirationDate'] = end_of_day_pacific.strftime('%Y-%m-%d %H:%M:%S%z')
except Exception as e:
current_app.logger.debug(f"Error parsing expirationDate: {str(e)}")
pass

# convert NWPTA dates to correct format
if json_input.get('nwpta', None):
Expand All @@ -777,8 +773,8 @@
if region['partnerNameDate'] == '':
region['partnerNameDate'] = None
if region['partnerNameDate']:
region['partnerNameDate'] = str(datetime.strptime(
str(region['partnerNameDate']), '%d-%m-%Y'))
partnerNameDateStr = region['partnerNameDate']
region['partnerNameDate'] = DateUtils.parse_date_string(partnerNameDateStr, '%d-%m-%Y')
except ValueError:
pass
# pass on this error and catch it when trying to add to record, to be returned
Expand Down
61 changes: 61 additions & 0 deletions api/namex/resources/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import re
from datetime import datetime


class DateUtils:
# Regex patterns to match the date string formats
# example: "Mon, 18 Sep 2023 23:13:36 UTC"
date_pattern1 = r'^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} UTC$'
# example: "2023-09-18T23:13:36+00:00"
date_pattern2 = r'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[\+\-]\d{2}:\d{2}$'
# example: "2023-09-18 23:13:36.186029+00"
date_pattern3 = r'^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{6}[\+\-]\d{2}$'

class DateParseException(Exception):
"""Custom exception for date parsing errors"""
pass

@staticmethod
def parse_date(date_str):
parsed_date = None

# Check if the date string matches the first pattern
if re.match(DateUtils.date_pattern1, date_str):
try:
# If it matches, parse the date string with the first format
parsed_date = datetime.strptime(date_str, '%a, %d %b %Y %H:%M:%S %Z')
except ValueError as e:
raise DateUtils.DateParseException(f"Error parsing date with format '%a, %d %b %Y %H:%M:%S %Z': {e}")

# Check if the date string matches the second pattern
elif re.match(DateUtils.date_pattern2, date_str):
try:
# If it matches, parse the date string with the second format
parsed_date = datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%S%z')
except ValueError as e:
raise DateUtils.DateParseException(f"Error parsing date with format '%Y-%m-%dT%H:%M:%S%z': {e}")

# Check if the date string matches the third pattern
elif re.match(DateUtils.date_pattern3, date_str):
try:
# If it matches, parse the date string with the third format
parsed_date = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S.%f%z')
except ValueError as e:
raise DateUtils.DateParseException(f"Error parsing date with format '%Y-%m-%d %H:%M:%S.%f%z': {e}")

# If no match for the predefined patterns, try to parse with datetime.fromisoformat
else:
try:
parsed_date = datetime.fromisoformat(date_str)
except ValueError as e:
raise DateUtils.DateParseException(f"Error parsing date with datetime.fromisoformat: {e}")

if parsed_date is None:
raise DateUtils.DateParseException(f"Unable to parse date: {date_str}")

return parsed_date

@staticmethod
def parse_date_string(date_str, output_date_format):
parsed_date = DateUtils.parse_date(date_str)
return parsed_date.strftime(output_date_format)