[英]parse time to proper format python
我有從網站解析時間的問題。
時間以這種格式給出(9-10:40AM,11-1:30PM,6:30-7:20PM)
如果時間不可用,它將顯示為TBA
我想以12H格式解析開始和結束時間。
此方法不返回正確的值例如,如果字符串是“11:25-12:15PM”,我希望得到[上午11:25,下午12:15]但我實際得到的是[11:25 PM,12 :15PM]
def insertTime(initialTime):
if "TBA" in initialTime:
return ["TBA", "TBA"]
startTime,endTime = initialTime.split("-")
try:
if "PM" in endTime:
startTimeHours = startTime.split(":")[0]
if ":" in startTime:
startTimeMinutes = ":" + startTime.split(":")[1]
else:
startTimeMinutes = ":00"
if int(startTimeHours) in range(9,12):
startTimeHours += startTimeMinutes + "AM"
if ":" not in startTime:
startTime +=":00"
if "AM" not in startTime:
startTime += endTime[-2:]
return [startTime, endTime]
except Exception as e:
print(f"Error insertTime: Start-> {startTime}, endTime->{endTime}")
print(e)
return [0,0]
謝謝
我認為如果你明確處理兩個可能的情況(AM和PM)為開始時間將是最簡單的:
import datetime
def parse_time(text):
pm = None # unknown
if text[-2:] in ('AM', 'PM'):
pm = (text[-2:] == 'PM')
text = text[:-2]
if ':' not in text:
text += ':00'
hours, minutes = text.split(':')
hours = int(hours)
minutes = int(minutes)
if pm and hours < 12:
hours += 12
return datetime.time(hours, minutes), pm is not None
def parse_interval(text):
if 'TBA' in text:
return None, None
start, end = text.split('-')
start, is_exact = parse_time(start)
end, _ = parse_time(end) # end time should be exact
# If both the start and end times are known then there's nothing left to do
if is_exact:
return start, end
# start2 = start + 12 hours
start2 = start.replace(hour=(start.hour + 12) % 24)
start_AM, start_PM = sorted([start, start2])
# Pick the most reasonable option
if start_AM < end < start_PM:
return start_AM, end
elif start_AM < start_PM < end:
return start_PM, end
else:
raise ValueError('This cannot happen')
if __name__ == '__main__':
for text in [
'9-10:40AM',
'11-1:30PM',
'6:30-7:20PM',
'11:25-12:15PM',
'2AM-12:15PM',
]:
print(text.rjust(15), ':', *parse_interval(text))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.