Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

python - How to parse date days that contain "st", "nd", "rd", or "th"?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...