Fastest way to insert these dashes in python string?

前端 未结 8 1503
失恋的感觉
失恋的感觉 2021-02-13 16:34

So I know Python strings are immutable, but I have a string:

c[\'date\'] = \"20110104\"

Which I would like to convert to

c[\'da         


        
相关标签:
8条回答
  • 2021-02-13 17:23

    I am not sure if you want to convert it to a proper datetime object or rather just hard code the format, you can do the following:

    from datetime import datetime
    result = datetime.strptime(c['date'], '%Y%m%d')
    print result.date().isoformat()
    

    Input: '20110104'

    Output: '2011-01-04'

    0 讨论(0)
  • 2021-02-13 17:24

    I'd probably do so this way, not that there's a great deal of gain:

    d = c['date']
    c['date'] = '%s-%s-%s' % (d[:4], d[4:6], d[6:])
    

    The big improvement (imho) is avoiding string concatenation.

    0 讨论(0)
提交回复
热议问题