chuky pedro
chuky pedro

Reputation: 747

What is the pythonic way to convert day and month in string format to date in python

I have day and month in string format 23rd Sep, I would like to convert the above string to the current date 23/09/2021. I achieved that using the below code, what is the more pythonic way to do this.?

from datetime import datetime

# datetime object containing current date and time
now = datetime.now()
year = str(now).split('-')
year =year[0]
dm = '23rd Sep'
s = re.findall(r'[A-Za-z]+|\d+', dm)
day_month = " ".join(s[::len(s)-1] )
date = day_month +' ' + year
dmap = {'Jan':'January','Feb':'Febuary','Mar':'March','Sep':'September'}
import arrow
for i in dmap.keys():
    s = date.split(' ')
    if i in s:
        s[1] = dmap[i]
        clean_date = ' '.join(s)
        p = arrow.get(clean_date, 'DD MMMM YYYY').format('DD/MM/YYYY')
print(p)

Upvotes: 0

Views: 86

Answers (2)

SeaBean
SeaBean

Reputation: 23207

You can use pd.to_datetime() to get current date and extract year from it. (No need to hardcode year)

Then, use it again for date conversion. Followed by strftime() for formatting date string.

import pandas as pd

year = pd.to_datetime('now').year     # Get current year
dm = '23rd Sep'

pd.to_datetime(dm + ' ' + str(year)).strftime('%d/%m/%Y')

Output:

'23/09/2021'

Upvotes: 1

ifly6
ifly6

Reputation: 5331

I don't see the problem:

import pandas as pd

s = '23rd Sep'
pd.Timestamp(s + ' 2021')
Out[1]: Timestamp('2021-09-23 00:00:00')

If you want it in DMY format:

_.strftime('%d/%m/%Y')
Out[2]: '23/09/2021'

Upvotes: 2

Related Questions