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

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
fricadelle
  • 511
  • 1
  • 8
  • 26

3 Answers3

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.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
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)
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
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')
Lupanoide
  • 3,132
  • 20
  • 36