我在从网站解析时间时遇到问题。
时间以这种格式(9-10:40 AM、11-1:30 PM、6:30-7:20PM)给出
如果时间不可用,它将显示为TBA
我想解析12H格式的开始和结束时间。
此方法未返回正确的值 例如,如果字符串是“ 11:25-12:15PM”,则我希望得到的是[11:25 AM,12:15 PM],但实际上我得到的是[11:25 PM,12:15 PM]
public Completable updateUserPhotoURL(Uri photoURL, UserProfileChangeRequest profileUpdates) {
return Completable.create(emitter -> {
if (mFirebaseUser == null) {
emitter.onError(new Exception("Firebase User is not initiated"));
}
RxFirebaseUser.updateProfile(mFirebaseUser, profileUpdates).complete()
.subscribe(new DisposableCompletableObserver() {
@Override
public void onComplete() {
emitter.onComplete();
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
emitter.onError(e);
}
});
});
}
谢谢
答案 0 :(得分:0)
我认为,如果您在开始时明确处理了两种可能的情况(上午和下午),那将是最简单的:
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))