python完成下面的时间格式的转换?

20180402:154101 -> 2018-04-02 15:41:51

clipboard.png
麻烦各位看看,谢谢了

阅读 2.3k
3 个回答

datetime库就好了

>>> from datetime import datetime
>>> old = '20180402:154101'
>>> dt = datetime.strptime(old, '%Y%m%d:%H%M%S')
>>> new = dt.strftime('%Y-%m-%d %X')
>>> print(new)
2018-04-02 15:41:01

当然你也可以纯用字符串处理达到相同的效果

这样?datetime.datetime.strptime('20180402:154101', '%Y%m%d:%H%M%S')

刚才自己写的
def TimeFormat(str):

pdb.set_trace()
#20180402:154101 -> 2018-04-02 15:41:01
time_stamp = ""
index = 0 
for c in str:
    if index == 4 or index == 6:
        time_stamp += '-' 
    if index == 8:
        time_stamp += ' ' 
        index = index + 1 
        continue
    if index == 11 or index == 13: 
        time_stamp += ':' 

    index = index + 1 
    time_stamp += c
    
return time_stamp
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题