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

怎样转换日期格式?

  •  
  •   omg21 · Jun 17, 2016 · 3998 views
    This topic created in 3602 days ago, the information mentioned may be changed or developed.
    import time
    from datetime import *
    str='2016/06/10'
    time_format = datetime.strptime(str, '%Y-%m-%d')
    print(time_format)

    我想把日期格式 2016/06/10 转换成 2016-06-10 ,可是上边的代码执行出错,为什么?
    还有,‘ 16/06/10 ’如何转换成‘ 2016-06-10 ’?
    13 replies    2016-06-18 04:17:11 +08:00
    omg21
        1
    omg21  
    OP
       Jun 17, 2016
    还有,‘ 16/06/10 ’如何转换成‘ 2016-06-10 ’?
    Livid
        2
    Livid  
    MOD
    PRO
       Jun 17, 2016   ❤️ 1
    你需要先把字符串转换成日期时间对象,然后再转换任何格式都会很简单。另外就是,可以看看这个库:

    http://crsmithdev.com/arrow/
    terence4444
        3
    terence4444  
       Jun 17, 2016 via iPhone
    你漏了使用 strftime 那一步
    oclock
        4
    oclock  
       Jun 17, 2016
    arrow +1
    rapospectre
        5
    rapospectre  
       Jun 17, 2016
    既然都是字符串为啥不直接 str.replace('/', '-')
    mulog
        6
    mulog  
       Jun 17, 2016
    人生苦短 早用 arrow 早享受。。
    wowo2088
        7
    wowo2088  
       Jun 17, 2016
    str.replace('/', '-') +1
    aitaii
        9
    aitaii  
       Jun 17, 2016
    字符串 直接替换就好了
    wmttom
        10
    wmttom  
       Jun 17, 2016
    自从用了 arrow ,就可以手写一切时间转化了
    practicer
        11
    practicer  
       Jun 17, 2016   ❤️ 1
    t = datetime.datetime.strptime(str, '%Y/%M/%d').strftime('%Y-%M-%d')

    datetime.datetime.strptime() 解析时间类字符串,返回 datetime 对象
    datetime.datetime.strftime()相反,将 datetime 对象转成实践类的字符串
    omg21
        12
    omg21  
    OP
       Jun 17, 2016
    @practicer 谢谢,已经解决了,但是现在又出来一个新问题,“ 2016 年 06 月 10 日”这个怎么转成 2016-06-10 ?
    practicer
        13
    practicer  
       Jun 18, 2016
    re.sub(u'^(\d+) 年 (\d+) 月 (\d+) 日$', r'\1-\2-\3', str)
    这种情况最好用 re 模块的替换函数了
    r'\1-\2-\3'里面\1 \2 \3 分别表示 group(1), group(2), group(3),记得不能省略 r ,也不能省略前面 regex 语句的 u
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5383 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 66ms · UTC 09:36 · PVG 17:36 · LAX 02:36 · JFK 05:36
    ♥ Do have faith in what you're doing.