推荐学习书目
› 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
fankcoder
V2EX  ›  Python

请教个问题,关于时间字符串比较大小

  •  
  •   fankcoder ·
    fankcoder · Oct 12, 2018 · 4091 views
    This topic created in 2945 days ago, the information mentioned may be changed or developed.

    time1 = "20181010" time2 = "20181012"

    这两个时间比较大小,转为时间戳或字符串直接比较都有结果

    我想问如果用简单方法(字符串)直接比较会不会有什么缺点(隐患)?

    10 replies  •  2018-10-17 14:25:26 +08:00
    ThirdFlame
    ThirdFlame
    Oct 12, 2018❤️1
    1
    你要是能保证格式绝对都是 yyyymmdd 那么用字符串比较也没问题。
    字符串比较的时候是从左往右逐个比较的 按照 ascii 值进行的。 不存在大数字比小数字 ascii 值小的情况。


    但是就是格式有异常的,那就可能出错了。
    crab
    crab
    Oct 12, 2018❤️1
    2
    只是到日期直接字符串
    ranoff
    ranoff
    Oct 12, 2018❤️1
    3
    格式有保障的话直接比较,没有的话还是先转一下比较好
    xFrank
    xFrank
    Oct 12, 2018❤️1
    4
    可以先转化为 datetime.datetime,然后就可以计算差值,比较大小了
    zivyou
    zivyou
    Oct 12, 2018❤️1
    5
    先做参数校验,再直接比较字符串,比较稳妥。
    fankcoder
    fankcoder
    OP
    Oct 12, 2018
    6
    好的,感谢~
    qbmiller
    qbmiller
    Oct 12, 2018❤️1
    7
    这种是不是 可以直接 int 比较了...
    ClutchBear
    ClutchBear
    Oct 12, 2018
    8
    直接比较的缺陷是
    比如 20180809
    可以写成 2018809
    这样比较就有可能出错了,
    最好转成 datetime.datetime
    JCZ2MkKb5S8ZX9pq
    JCZ2MkKb5S8ZX9pq
    Oct 12, 2018
    9
    格式有保证的话直接 int 就好了,甚至不考虑好读的话,可以 timestamp//86400 更短一点。
    jeadong
    jeadong
    Oct 17, 2018
    10
    前一段时间我也做过比较,然后我就说一句,MS 的时间原点和 LINUX 的时间原点不是同一天。
    如果你从 EXCEL 里提取日期,要考虑这个。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2168 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 16:03 · PVG 00:03 · LAX 08:03 · JFK 11:03
    ♥ Do have faith in what you're doing.