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

将时间转化为数值有没有更好的办法

  •  
  •   songdg · 2018-12-22 22:19:17 +08:00 · 2129 次点击
    这是一个创建于 1923 天前的主题,其中的信息可能已经有所发展或是发生改变。
    tt = datetime.datetime(2018, 12, 22, 22, 30, 45)
    想得到一个整数 223045,除了 int(str(tt.hour) + str(tt.minute) + str(tt.second))之外有没有其他的方法。
    11 条回复    2018-12-23 19:12:45 +08:00
    AlisaDestiny
        1
    AlisaDestiny  
       2018-12-22 22:31:05 +08:00   ❤️ 1
    tt.strftime("%H%M%S")
    takato
        2
    takato  
       2018-12-22 22:34:27 +08:00   ❤️ 1
    tt.timestamp()
    takato
        3
    takato  
       2018-12-22 22:36:51 +08:00
    抱歉,没看到想要的是特定格式的整数,如果对数字格式有要求请使用#1 答案,使用 timestamp 可以保留较高的精度。
    Kagari
        4
    Kagari  
       2018-12-22 22:36:59 +08:00
    1L 正解,或者直接存时间戳( 2L )
    Herobs
        5
    Herobs  
       2018-12-22 22:40:05 +08:00 via Android
    reduce(lambda sum, x: x + sum*100, [tt.hour, tt.minute, tt.second])

    当只有一位数的时候,你这是有 bug 的
    silkriver
        6
    silkriver  
       2018-12-22 22:43:48 +08:00   ❤️ 1
    这样也可以,python 3.6 以上
    f"{tt.hour}{tt.minute}{tt.second}"
    silkriver
        7
    silkriver  
       2018-12-22 22:54:36 +08:00
    这样写更好一点
    f"{tt:%H%M%S}"
    gainsurier
        8
    gainsurier  
       2018-12-22 23:11:16 +08:00
    直接用#2 楼的办法,用时间戳保存。
    songdg
        9
    songdg  
    OP
       2018-12-23 19:11:46 +08:00
    @AlisaDestiny 谢谢帮助。
    songdg
        10
    songdg  
    OP
       2018-12-23 19:12:11 +08:00
    @takato 感谢帮助。
    songdg
        11
    songdg  
    OP
       2018-12-23 19:12:45 +08:00
    @silkriver 多谢帮助。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2426 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 16:09 · PVG 00:09 · LAX 09:09 · JFK 12:09
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.