Reputation: 15310
What is the best way to convert the following date pattern to a datetime.date
object in Python?
1st April
8th April
15th April
1st May
Upvotes: 1
Views: 429
Reputation: 9826
dateutil.parser
will parse almost every known date format:
from dateutil.parser import parse
parse('8th April')
To always get a date in the future:
from dateutil.parser import parse
from datetime import datetime
d = parse('8th April')
if (d - datetime.now()).days <= 0:
d = datetime.date(d.year+1, d.month, d.day)
Upvotes: 4
Reputation: 2932
from datetime import datetime
val = val.replace('th', '').replace('st', '')
d = datetime.strptime(val, '%d %B')
Upvotes: 0