Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 538
Marco Dinatsoli Avatar asked Feb 01 '14 09:02

Marco Dinatsoli


People also ask

How do you parse time from a date?

The parse() method takes a date string (such as "2011-10-10T14:48:00" ) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the setTime() method and the Date object.

How do you parse a date format in Python?

Python has a built-in method to parse dates, strptime . This example takes the string “2020–01–01 14:00” and parses it to a datetime object. The documentation for strptime provides a great overview of all format-string options.

How do I get the month and day from a date in python?

To extract only the month and day from a datetime object in Python, we can use the DateFormatter() class.


2 Answers

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)
like image 84
Ashwini Chaudhary Avatar answered Nov 14 '22 16:11

Ashwini Chaudhary


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

like image 39
FallenAngel Avatar answered Nov 14 '22 15:11

FallenAngel