【Python程式設計】時間轉換器案例
阿新 • • 發佈:2019-01-26
#!/usr/bin/env python
# -*- coding:utf8 -*-
from datetime import datetime
from dateutil import parser
import re
import sys
Count = True
ch = r"[\u4e00-\u9fa5]"
en = r"^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$"
class TimeMaster:
def __init__(self, your_time, fmt_time="%Y-%m-%d %X"):
self.your_time = your_time
self. fmt_time = fmt_time
def config_time_en(self):
date1 = parser.parse(self.your_time)
date1_result = date1.strftime(self.fmt_time)
print(f"轉換時間成功,轉換時間為{date1_result}")
def config_time_ch(self):
date2 = self.your_time.replace("年", "/").replace("月", "/").replace( "日", "/")
date2_now = parser.parse(date2)
date2_result = date2_now.strftime(self.fmt_time)
print(f"轉換時間成功,轉換時間為{date2_result}")
def config_time_num(self):
month, day = self.your_time.split(".")
date_now = datetime.now()
my_time = date_now.replace( day=int(day), month=int(month))
time_result = my_time.strftime(self.fmt_time)
print(f"轉換時間成功,轉換時間為{time_result}")
while(Count):
print("""
time_1:11.6
time_2: 2018年11月6日
time_3: 2018/11/06
退出:輸入'exit'即可
""")
Your_date = input("請您輸入一個日期:")
if re.search(ch, Your_date):
Your_time = TimeMaster(Your_date)
Your_time.config_time_ch()
elif re.search(en, Your_date):
Your_time = TimeMaster(Your_date)
Your_time.config_time_num()
elif re.search("/", Your_date):
Your_time = TimeMaster(Your_date)
Your_time.config_time_en()
elif Your_date == "exit":
print("退出成功!!!")
sys.exit()
else:
print("輸入時間不正確,請您重新輸入時間格式.")
Count = True