0

Would anyone know a regex string or another method of obtaining the date and time from this string into variables? The position of the string could change, so line and char no would not work. This is a bit beyond my ability, can it be done?

Thanks

Dear Customer,

(Call Transferred) Start Time & Date: 00:05 Monday 6th February 2017               
Completion Time & Date: 06:00 Monday 6th February 2017                 

Details of Work:
4
  • 2
    use the DateTime Commented Jan 26, 2017 at 10:43
  • you suggest using regex - what have you tried? Commented Jan 26, 2017 at 10:45
  • Your original title said "date" but your question body says "date and time", which is different. Then you say "obtain the date and time as variables", i.e. two separate items; but there are types which combine those in one (datetime and DateType) Commented Jun 29, 2024 at 5:14
  • Also, your source format can vary, so this is called 'parsing' the date-and-time format, not just 'get'. Commented Jun 29, 2024 at 8:39

1 Answer 1

2

This works with the example report you've provided. It returns both the start and completion date and should handle day-of-month suffixes like 'th', 'rd', etc.

import re

import dateutil.parser

REPORT = \
"""Dear Customer,

(Call Transferred) Start Time & Date: 00:05 Monday 6th February 2017
Completion Time & Date: 06:00 Monday 6th February 2017

Details of Work:"""


def parse_report(data):
    dates = []

    for pattern in ['(?<=Start Time & Date: ).*', '(?<=Completion Time & Date: ).*']:
        date = dateutil.parser.parse(re.search(pattern, data).group(0))
        dates.append(date)

    return dates


if __name__ == '__main__':
    start, completion = parse_report(REPORT)
    print('Started: {}, Completed: {}'.format(start, completion))

Output

Started: 2017-02-06 00:05:00, Completed: 2017-02-06 06:00:00

Edit

Updated to use dateutil.parser instead which simplifies the code (thanks to asongtoruin for the suggestion).

Sign up to request clarification or add additional context in comments.

2 Comments

you could use dateutil.parser.parse() rather than datetime.strptime() to remove the need to filter_day_of_month_suffix()?
@asongtoruin Thanks, wasn't aware of that package.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.