我可以有一個日期字串,例如:
4.3.2009 (my output is 'day' because user meant a day)
3.2009 (my output is 'month' because user meant March)
4/3/2009 (same - output is day)
4-2009 ( output is month)
我dateutil用來決議字串但無法檢查格式。我只需要知道type,不管它是'month','M'還是其他輸出。我知道我可以詢問格式, datetime.strftime(string,format)但這無濟于事。
uj5u.com熱心網友回復:
對于多樣性匹配,您可以使用正則運算式re。
(\d{1,2}\D ?)?(\d{1,2}\D ?\d{4})
匹配成功且第1組有值時,表示
day,匹配成功且第1組無值時,表示month。
import re
dates_str = ['4.3.2009', '3.2009', '4/3/2009', '4-2009']
regex = re.compile(r"(\d{1,2}\D ?)?(\d{1,2}\D ?\d{4})")
def func(v):
res = regex.match(v)
if res:
if all(res.groups()):
return "day"
else:
return "month"
return ""
for date_str in dates_str:
print(func(date_str))
輸出:
day
month
day
month
uj5u.com熱心網友回復:
您可以通過像這樣拆分日期字串來做到這一點:
dates = ['4.3.2009', '3.2009', '4/3/2009', '4-2009']
def check(date):
for c in date:
if not c.isdigit():
t = date.split(c)
if len(t) == 2:
return 'month'
if len(t) == 3:
return 'day'
break
return None
for date in dates:
print(check(date))
輸出:
day
month
day
month
筆記:
如果輸入字串不包含看起來像日期的內容,則 check() 函式將回傳 None。它不驗證給定的字串。例如,“99-99-99”將回傳“天”。您可以擴展函式以根據識別的分隔符構建 strptime 格式字串
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/412826.html
標籤:
上一篇:日期時間(以位元組為單位)
