将平面字符串转换为 Python 中的日期格式
Convert a plane string to date format in Python
我有一个平面文本,如“20211111012030”,需要将其转换为“YYYY-MM-DD HH:MM:SS”(2021-11-11 01:20:30) python 中的格式。如何将其转换为上述特定格式
您可以使用正则表达式方法:
inp = '20211111012030'
output = re.sub(r'(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})', r'-- ::', inp)
print(output) # 2021-11-11 01:20:20
使用 datetime
包。
from datetime import datetime
dt_str = '20211111012030'
dt = datetime.strptime(dt_str, '%Y%m%d%H%M%S')
print(dt)
我有一个平面文本,如“20211111012030”,需要将其转换为“YYYY-MM-DD HH:MM:SS”(2021-11-11 01:20:30) python 中的格式。如何将其转换为上述特定格式
您可以使用正则表达式方法:
inp = '20211111012030'
output = re.sub(r'(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})', r'-- ::', inp)
print(output) # 2021-11-11 01:20:20
使用 datetime
包。
from datetime import datetime
dt_str = '20211111012030'
dt = datetime.strptime(dt_str, '%Y%m%d%H%M%S')
print(dt)