V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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 · 3662 views
    This topic created in 2764 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
        1
    ThirdFlame  
       Oct 12, 2018   ❤️ 1
    你要是能保证格式绝对都是 yyyymmdd 那么用字符串比较也没问题。
    字符串比较的时候是从左往右逐个比较的 按照 ascii 值进行的。 不存在大数字比小数字 ascii 值小的情况。


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