如何转换" _20161002_1630 _"进入" 2016/10/02 16:30:00"使用python?
输入=" _20161002_1630 _"
预期产量= 2016/10/02 16:30:00
答案 0 :(得分:0)
#usr/bin/python
input = "_20161002_1630_"
# removing _ from start and end
string = input[1:-1]
#seprating date and time
date, time = string.split("_")
# formatting date
formatted_date = date[:4] + "/" + date[4:6] + "/" + date[6:]
# adding zeros to make time into hrsminsseconds
time = (time + "00") if len(time) < 5 else time
#formatting time
formatted_time = time[:2] + ":" + time[2:4] + ":" + time[4:]
# rejoining output
output = formatted_date + " " + formatted_time
答案 1 :(得分:0)
您可以使用re
模块来帮助完成任务。以下翻译会话显示了如何:
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import re
>>> old_date = '_20161002_1630_'
>>> new_date = '{year}/{month}/{day} {hour}:{minute}:00'.format(
**re.search(r'^[^\d]+(?P<year>\d{4})(?P<month>\d{2})(?P<day>\d{2})'
r'[^\d]+(?P<hour>\d{2})(?P<minute>\d{2})[^\d]+$', old_date)
.groupdict())
>>> print(new_date)
2016/10/02 16:30:00
>>>