推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
gogobody
V2EX  ›  Python

请问 Python 判断 2 个时间段是否有交集 有什么好的方法吗?

  •  
  •   gogobody · Aug 22, 2017 · 9607 views
    This topic created in 3370 days ago, the information mentioned may be changed or developed.

    时间为 datetime 对象。 start_time1 , end_time1 和 start_time2 , end_time2 判断这 2 个时间段是否有交集有什么好的方法吗?我只会用 if 按照条件判断,感觉很笨重。 请教各位 V 友!

    Supplement 1  ·  Aug 23, 2017
    #感谢前 10L 的 V 友
    突然忘了。。。其实是多个时间段,并不止 2 个。。。对不起 TQT
    情况是这样,判断时间是 1 天,用户发起了一些活动(包含持续时间),也就是说开始时间,结束时间确定了。然后用户再发起新的活动就要判断时间段时间段是否冲突。。。
    14 replies  •  2017-08-23 09:55:10 +08:00
    zhjits
    zhjits
    Aug 22, 2017
    1
    start_time1 < start_time2 < end_time1 or start_time2 < start_time1 < end_time2
    autoxbc
    autoxbc
    Aug 22, 2017
    2
    无交集
    start_time1 < end_time2 || start_time2 < end_time1
    有交集
    上面取反
    lcdtyph
    lcdtyph
    Aug 22, 2017 via iPhone❤️1
    3
    @autoxbc 你再考虑一下…
    lcdtyph
    lcdtyph
    Aug 22, 2017 via iPhone❤️3
    4
    max(start1, start2)<min(end1, end2)就相交了
    am241
    am241
    Aug 22, 2017 via Android
    5
    (s2-e1)*(s1-e2) < 0
    wisej
    wisej
    Aug 22, 2017 via Android❤️1
    6
    @autoxbc 感觉 应该都是>?
    autoxbc
    autoxbc
    Aug 22, 2017
    7
    @lcdtyph #3
    @wisej #6
    嗯,写完发现反了,意思到了就行
    blankme
    blankme
    Aug 23, 2017
    8
    记两组数据为(x1, x2) (y1, y2)
    它们有交集的条件是:

    arctan(y2/x1) > 1 && arctan(y1/x2) < 1
    blankme
    blankme
    Aug 23, 2017
    9
    @blankme
    写错了,应该是 tan,而不是 arctan
    Or2
    Or2
    Aug 23, 2017 via Android❤️1
    10
    好奇为啥没人说是 S 2 -E1 <0
    wisej
    wisej
    Aug 23, 2017
    11
    设 a 为 各个活动持续时间之和
    设 b 为 max(E1,E2,...,EN) - min(S1,S2,...,SN)
    如果 a > b,说明有交集
    u2386
    u2386
    Aug 23, 2017 via iPhone
    12
    @Or2 同好奇
    momo1999
    momo1999
    Aug 23, 2017
    13
    @Or2 咦,好像就这么简单啊
    momo1999
    momo1999
    Aug 23, 2017❤️1
    14
    @Or2 错了,这样有可能不相交的,S1>E2
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1102 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 52ms · UTC 18:34 · PVG 02:34 · LAX 10:34 · JFK 13:34
    ♥ Do have faith in what you're doing.