I have a plane text like '20211111012030' and need to convert it to 'YYYY-MM-DD HH:MM:SS'(2021-11-11 01:20:30) format in python .How can I convert it to a specific format as above
Asked
Active
Viewed 55 times
2 Answers
1
Use the datetime
package.
from datetime import datetime
dt_str = '20211111012030'
dt = datetime.strptime(dt_str, '%Y%m%d%H%M%S')
print(dt)

过过招
- 3,722
- 2
- 4
- 11
0
You could use a regex approach:
inp = '20211111012030'
output = re.sub(r'(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})', r'\1-\2-\3 \4:\5:\5', inp)
print(output) # 2021-11-11 01:20:20

Tim Biegeleisen
- 502,043
- 27
- 286
- 360