簡體   English   中英

將格式化字符串轉換為日期時間

[英]Converting a formatted string into date time

我有一個這種格式的字符串:

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

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

下面是字符和月份的映射:

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
              }

我想以 yyyymmdd 格式找出本月的最后一個營業日期。 有人可以幫助我嗎?

我正在嘗試執行以下操作:

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])

使用regexdatetimecalendar

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
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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM