Python 中文日期轉換
3 min readFeb 9, 2021
關鍵字: Python 日期字串、轉換
如題,如果 input 很單純是 XXX 年 XX 月 XX 日的話,做法其實很簡單…
BUT…
input 可能會有 109.12.31,1091231,109年.12月.31日.,各種亂七八糟的狀況XD,所以在判斷上就要有更多彈性~
import re
from datetime import dateDELIM = u'[.年月日/-]'
CHINESE_JANUARY = u'元月'
ENGLISH_JANUARY = u'1月'
ERA_AD_TO_ROC = 1911def date_convert(input_str):
if input_str == '':
return input_str if re.findall(CHINESE_JANUARY, input_str):
converted_str = input_str.replace(CHINESE_JANUARY, ENGLISH_JANUARY)
else:
converted_str = input_str date_list = [x for x in re.split(DELIM, converted_str) if x is not '']
date_list_len = len(date_list) # The date would be parsed by fixed position
# when input date whitout delim or not complete.
try:
if date_list_len == 1:
year = int(date_list[0][:-4])
month = int(date_list[0][-4:-2])
day = int(date_list[0][-2:])
elif date_list_len == 2:
return "fail: " + input_str
elif date_list_len > 3:
return "fail: " + input_str
else:
year = int(date_list[0])
month = int(date_list[1])
day = int(date_list[2])
except:
return "fail: " + input_str # convert era from A.D. to ROC
if year > ERA_AD_TO_ROC:
year -= ERA_AD_TO_ROC ret_str = ''
try:
date(year, month, day)
except:
return "fail: " + input_str try:
ret_str += ("{:d}".format(int(year)))
ret_str += ("{:02d}".format(int(month)))
ret_str += ("{:02d}".format(int(day)))
except:
return "fail: " + input_str return ret_str