Dr. Ac
Dr. Ac

Reputation: 11

convert element and next element in list of strings to date in python

I am new to Python and am having trouble with the following string:

Order now for free delivery loose on Tuesday, April 25 or set in jewelry on Tuesday, April 29.

I have converted it to a list of strings with .split(). However, I cannot figure out how to iterate through the list to pull out the dates such as April 25 and April 29. Once I pull these strings out, I know I can convert them to a date format with datetime.strptime(string, '%B %d') with string being "April 25" and "April 29" and can apply a date-diff function.

I think I need to pull both list elements that contain month names as strings and the next element with the day of the month to combine them in order to convert them to date format.

Any assistance would be much appreciated. Thank you in advance.

Upvotes: 1

Views: 91

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

If it's intended for the current 2017 year, the solution using
calendar.day_name (the days of the week),
calendar.month_name (the months of the year)
and datetime.strptime() function:

import calendar, datetime

s = 'Order now for free delivery loose on Tuesday, April 25 or set in jewelry on Tuesday, April 29'
day_names = '|'.join(list(calendar.day_name))  # Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday
month_names = '|'.join(list(calendar.month_name[1:]))
dates = re.findall(r'((' + day_names + '), (' + month_names + ') \d{1,2})', s)
datetimes = [datetime.datetime.strptime(d[0] + ' 2017', '%A, %B %d %Y') for d in dates]

print(datetimes)

The output:

[datetime.datetime(2017, 4, 25, 0, 0), datetime.datetime(2017, 4, 29, 0, 0)]

Upvotes: 1

Jan
Jan

Reputation: 43169

Praise the power of regular expressions here:

import re
from datetime import datetime

s = "Order now for free delivery loose on Tuesday, April 25 or set in jewelry on Tuesday, April 29."

# regex looking for dates in the given format
rx = re.compile(r'''
            (?:(?:Mon|Tues|Wednes|Thurs|Fri|Satur|Sun)day),\s+
            (?:January|February|March|April|May|June|July|August|September|October|November|December)\s+
            \d+
            ''', re.VERBOSE)

dates = [datetime.strptime("{} #{}".format(m.group(0), "2017"), '%A, %B %d #%Y') 
        for m in rx.finditer(s)]
print(dates)
# [datetime.datetime(2017, 4, 25, 0, 0), datetime.datetime(2017, 4, 29, 0, 0)]

Upvotes: 2

Related Questions