Adam
Adam

Reputation: 483

Convert date string of format 1st, 2nd..nth-Month-YYYY to python date object

Can anyone help me with converting date strings like:

I cannot see in datetime.strptime() behaviour that it allows for this format.

Upvotes: 0

Views: 1102

Answers (3)

Anastasiya-Romanova 秀
Anastasiya-Romanova 秀

Reputation: 3378

Apparently I made a mistake in answering your question.

To convert a string to date without using regex, we can try

from datetime import datetime as dt
s = '22nd-October-1998'
dt.strptime(s.replace(s[s.find('-')-2:s.find('-')], ''), '%d-%B-%Y').date()

The idea is to find the character - and then replace 2 characters before - with an empty string then convert it using datetime.strptime().


In a DataFrame, we can do it by using pandas native functions. Suppose that the DataFrame is df and the date string format column is Date, then we can convert the column to date time format by using

    pd.to_datetime(df['Date'].replace(dict.fromkeys(['st', 'nd', 'rd', 'th'], ''),
                                      regex=True), format='%d-%B-%Y')

The idea is to replace the substrings ['st', 'nd', 'rd', 'th'] with an empty string then convert the column using pandas.to_datetime().

Upvotes: 0

Vim
Vim

Reputation: 578

You can still use strptime however you need to removed the extra chars in data using regex

import re
date_string = "1st-October-1998"
def remove_extra_chars(ds):                                             
    return re.sub(r'(\d)(st|nd|rd|th)', r'\1', ds)
d = datetime.strptime(solve(date_string), '%d-%B-%Y')
print(d.strftime('%d-%B-%Y')) # output: 01-October-1998
print(d.strftime('%Y-%m-%d')) # output: 1998-10-01

Upvotes: 0

Vikas Periyadath
Vikas Periyadath

Reputation: 3186

You can try with dateutil.pareser :

import dateutil.parser

s = "1st-October-1998"
d = dateutil.parser.parse(s)
print(d.date())

Output :

1998-10-01

Upvotes: 5

Related Questions