Skip to content

Commit

Permalink
fix: Guess more date formats
Browse files Browse the repository at this point in the history
Can guess the following formats now:
- 7 May 2020
- 1 Jan 2020
  • Loading branch information
netchampfaris committed Jul 9, 2020
1 parent 6e336fa commit 89d2c06
Showing 1 changed file with 36 additions and 30 deletions.
66 changes: 36 additions & 30 deletions frappe/utils/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -1258,6 +1258,8 @@ def guess_date_format(date_string):
r"%d.%m.%y",
r"%m.%d.%y",
r"%y.%m.%d",
r"%d %b %Y",
r"%d %B %Y",
]

TIME_FORMATS = [
Expand All @@ -1269,41 +1271,45 @@ def guess_date_format(date_string):
r"%I:%M %p",
]

date_string = date_string.strip()

_date = None
_time = None

if " " in date_string:
_date, _time = date_string.split(" ", 1)
else:
_date = date_string

date_format = None
time_format = None

for f in DATE_FORMATS:
try:
# if date is parsed without any exception
# capture the date format
datetime.datetime.strptime(_date, f)
date_format = f
break
except ValueError:
pass
def _get_date_format(date_str):
for f in DATE_FORMATS:
try:
# if date is parsed without any exception
# capture the date format
datetime.datetime.strptime(date_str, f)
return f
except ValueError:
pass

if _time:
def _get_time_format(time_str):
for f in TIME_FORMATS:
try:
# if time is parsed without any exception
# capture the time format
datetime.datetime.strptime(_time, f)
time_format = f
break
datetime.datetime.strptime(time_str, f)
return f
except ValueError:
pass

full_format = date_format
if time_format:
full_format += " " + time_format
return full_format
date_format = None
time_format = None
date_string = date_string.strip()

# check if date format can be guessed
date_format = _get_date_format(date_string)
if date_format:
return date_format

# date_string doesnt look like date, it can have a time part too
# split the date string into date and time parts
_date = None
_time = None

if " " in date_string:
date_str, time_str = date_string.split(" ", 1)

date_format = _get_date_format(date_str) or ''
time_format = _get_time_format(time_str) or ''

if date_format and time_format:
return (date_format + ' ' + time_format).strip()

0 comments on commit 89d2c06

Please sign in to comment.