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
JCZ2MkKb5S8ZX9pq
V2EX  ›  Python

Python 的 timestamp 处理小于 10 位的数字遇到的问题

  •  
  •   JCZ2MkKb5S8ZX9pq · 2018-10-27 22:50:20 +08:00 · 1845 次点击
    这是一个创建于 2007 天前的主题,其中的信息可能已经有所发展或是发生改变。
    • 之前一直没注意,原来fromtimestamp不能处理 10 位以内的时间。
    • utcfromtimestamp可以,但是不带时区。
    • 而且utcfromtimestamp支持负数,但只到 -43200,也就是半天,很微妙的数字。

    满隐蔽的一个坑点。速度倒是 utcfromtimestamp 快很多。
    那么问题来了,有啥能完美处理时间戳的方法嘛?

    datetime.fromtimestamp(1234567890)
    # 2009-02-14 07:31:30 东 8 区
    
    datetime.fromtimestamp(0)
    # error
    
    datetime.utcfromtimestamp(0)
    # 1970-01-01 00:00:00 不含时区
    
    datetime.utcfromtimestamp(1234567890)
    # 2009-02-13 23:31:30 不含时区
    
    datetime.utcfromtimestamp(-43200)
    # 1969-12-31 12:00:00
    
    第 1 条附言  ·  2018-10-28 00:37:51 +08:00

    自答

    • formtimestamp 支持的最小值是 86400 ,估计留一天是为了时差。
    • utcfromtimestamp 支持的最小值 -43200 ,估计也是为了时差。
    3 条回复    2018-10-28 00:55:16 +08:00
    oska874
        1
    oska874  
       2018-10-27 23:23:21 +08:00
    从来不看文档吗?
    ```
    fromtimestamp() may raise ValueError, if the timestamp is out of the range of values supported by the platform C localtime() or gmtime() functions. It ’ s common for this to be restricted to years in 1970 through 2038.
    ```
    JCZ2MkKb5S8ZX9pq
        2
    JCZ2MkKb5S8ZX9pq  
    OP
       2018-10-28 00:40:58 +08:00
    @oska874 厉害厉害,第一次碰到会看文档的大神。U •ェ• U
    Linxing
        3
    Linxing  
       2018-10-28 00:55:16 +08:00
    我操 我才知道原来可以这么用 我还是手动转换 localtime
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4363 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 21ms · UTC 01:04 · PVG 09:04 · LAX 18:04 · JFK 21:04
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.