Home > Software engineering >  Converting a formatted string into date time
Converting a formatted string into date time

Time:08-11

I have a string of this format :

a~b~c~[character][year]

eg:
x = a~b~c~f16 represent january 2016.

Below os the character and month mapping:

month_dict = {'F': 1,
              'G': 2,
              'H': 3,
              'J': 4,
              'K': 5,
              'M': 6,
              'N': 7,
              'Q': 8,
              'U': 9,
              'V': 10,
              'X': 11,
              'Z': 12
              }

I want to find out the last business date of this month in yyyymmdd format. Can someone help me in this?

I am trying to do the following:

m = x.split(~)
def last_business_day_in_month(year: int, month: int) -> int:
    return max(calendar.monthcalendar(year, month)[-1:][0][:5])



x = last_business_day_in_month(m[3][1:], month_dict[3][0])

CodePudding user response:

Use regex, datetime and calendar

import re
import datetime
import calendar

month_dict = {'F': 1,
              'G': 2,
              'H': 3,
              'J': 4,
              'K': 5,
              'M': 6,
              'N': 7,
              'Q': 8,
              'U': 9,
              'V': 10,
              'X': 11,
              'Z': 12
}

x = f"a~b~c~f16"

result = re.search("[f-z]\d ", x).group(0)
letter = result[0]
year = int(result[1:])
month = month_dict[letter.upper()]

last_business_day = max(calendar.monthcalendar(year, month)[-1:][0][:5])

date = datetime.datetime.strptime(f"{last_business_day} {month} {year}", "%d %m %y")
formatted_date = date.strftime("%Y%m%d")
print(formatted_date)

Output

20160129

CodePudding user response:

def last_business_day_in_month(year: int, month: int) -> int:
    return max(calendar.monthcalendar(year, month)[-1:][0][:5])  

m = x.split("~")
year = int(m[3][1:])
month = month_dict[m[3][0].upper()]
x = last_business_day_in_month(year, month)
  • Related