8

I have a string like this

"1st January 2014"

I want to parse it into a datetime.date. I can do this:

If the date is 1 January 2014 I make this: replace(' ','') then datetime.strptime(SecondDateString, "%d%B%Y").date()

But this doesn't work when the day has st, nd, rd, or th.

Edit: you may say that I myself remove the st, nd, rd, or th and then use my own way above, yes this is a solution but I am asking if python has already had something for me.

martineau
  • 119,623
  • 25
  • 170
  • 301
Marco Dinatsoli
  • 10,322
  • 37
  • 139
  • 253

2 Answers2

16

You can use regex to replace st, nd, rd, th with an empty string:

import re
def solve(s):                                             
    return re.sub(r'(\d)(st|nd|rd|th)', r'\1', s)

Demo:

>>> datetime.strptime(solve('1st January 2014'), "%d %B %Y")
datetime.datetime(2014, 1, 1, 0, 0)
>>> datetime.strptime(solve('3rd March 2014'), "%d %B %Y")
datetime.datetime(2014, 3, 3, 0, 0)
>>> datetime.strptime(solve('2nd June 2014'), "%d %B %Y")
datetime.datetime(2014, 6, 2, 0, 0)
>>> datetime.strptime(solve('1st August 2014'), "%d %B %Y")
datetime.datetime(2014, 8, 1, 0, 0)
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
7

You can use dateutil.parser module

date1 = "1st January 2014"
dateutil.parser.parse(date1)
>> datetime.datetime(2014, 1, 1, 0, 0)

You can check full documentation from here

Mp0int
  • 18,172
  • 15
  • 83
  • 114
  • 2
    Don't forget `import dateutil.parser` – GordonAitchJay Dec 18 '20 at 02:08
  • @FallenAngel this is amazing! But why oh why does python have both `datetime.strptime()` and also `dateutil.parser.parse()`? – BLimitless Jun 12 '21 at 05:07
  • @BLimitless because datetime is a python core module while dateutil is a 3rd party library. – Mp0int Jun 14 '21 at 08:56
  • @fallenangel Ah, that makes sense. I thought it was built in because I didn't have to pop install it It must have been installed automatically in my anaconda distribution. Thank you. – BLimitless Jun 14 '21 at 14:37