V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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
617450941
V2EX  ›  Python

python 怎么判断一个时间是否过期

  •  
  •   617450941 · 2015-10-26 21:48:20 +08:00 · 4517 次点击
    这是一个创建于 3076 天前的主题,其中的信息可能已经有所发展或是发生改变。
    比如在数据库取到一个到期日期是 2015-10-26 00:00:00 现在要用当前系统时间和这个数据库取到的时间做对比 判断是否到期 具体代码该怎么写
    3 条回复    2015-10-26 23:39:57 +08:00
    leavic
        1
    leavic  
       2015-10-26 23:17:21 +08:00
    >>> import datetime
    >>> datetime.datetime.now()
    woohaha
        2
    woohaha  
       2015-10-26 23:19:55 +08:00
    from datetime import datetime
    datetime_from_db='2015-10-26 00:00:00'
    datetime_of_datetime_from_db=datetime.strptime(datetime_from_db,'%Y-%m-%d %H:%M:%S')
    delta_time=datetime.now()-datetime_of_datetime_from_db
    if delta_time.days<0:
    print('expired')
    else:
    print('valid')
    DeanThompson
        3
    DeanThompson  
       2015-10-26 23:39:57 +08:00   ❤️ 1
    注意一下时区是否相同,如果相同就简单了:

    ```python
    import datetime

    def is_expired(dt):
    if isinstance(dt, str):
    dt = datetime.datetime.strptime(dt, '%Y-%m-%d %H:%M:%S')
    return datetime.datetime.now() > dt
    ```

    >>> is_expired('2015-10-26 00:00:00')
    True

    >>> is_expired('2015-11-26 00:00:00')
    False
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5418 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 08:49 · PVG 16:49 · LAX 01:49 · JFK 04:49
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.