Skip to content Skip to sidebar Skip to footer

Date Conversion With Strptime()

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

Solution 1:

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.parserimport 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)

Solution 2:

from datetime import datetime

val = val.replace('th', '').replace('st', '')
d = datetime.strptime(val, '%d %B')

Post a Comment for "Date Conversion With Strptime()"