0

how would you go about parsing a date like that in python:

     Monday, April 1st

I've tried

    datetime_object = datetime.strptime(date.replace("st","").replace("rd","").replace("th","").replace("nd","").strip(), '%A, %B %d')

But obviously it would remove the "nd" from "Monday" and cause an exception

thanks

3 Answers 3

2

Don't replace. Strip, from the right using str.rstrip. If the unwanted characters don't exist, the string is returned as is:

>>> from datetime import datetime
>>> s = "Monday, April 1st"
>>> datetime.strptime(s.rstrip('strndh'), '%A, %B %d')
datetime.datetime(1900, 4, 1, 0, 0)

Note that the day information here (i.e. Monday) is redundant.

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

1 Comment

yes this is perfect except we need to add 'n' to rstrip :)
1

You can use the dateutil module (pip install py-dateutil):

>>> from dateutil import parser
>>> parser.parse("Monday, April 1st")
datetime.datetime(2017, 4, 1, 0, 0)

Comments

0

Also if all your string doesn't have the same length:

a = "Monday, April 1st"
if not a[-1].isdigit():
    a = a[:-2]
datetime_object = datetime.strptime(a, '%A, %B %d')

Comments

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.