如何用python快速的算出两个时间段中重叠的天数
-
比如一个时间段是:2018年1月15日到2018年5月10日
另一个时间段是:2018年3月20日到2018年9月15日
计算重叠天数>>> from datetime import datetime >>> from collections import namedtuple >>> Range = namedtuple('Range', ['start', 'end']) >>> r1 = Range(start=datetime(2018, 1, 15), end=datetime(2018, 5, 10)) >>> r2 = Range(start=datetime(2018, 3, 20), end=datetime(2018, 9, 15)) >>> latest_start = max(r1.start, r2.start) >>> earliest_end = min(r1.end, r2.end) >>> delta = (earliest_end - latest_start).days + 1 >>> overlap = max(0, delta) >>> overlap 52 -
@萧云飞 感谢提供你的方案,棒!
解决的思路是类似的,不过兄弟没有考虑当两个时间段没有交集的情况:face_with_stuck-out_tongue_winking_eye:@digitalsatori 就是,哈哈,被您一说,才发现。这个就只能提前判断是否有交汇了

Hello! It looks like you're interested in this conversation, but you don't have an account yet.
Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.
With your input, this post could be even better 💗
Register Login