天天看點

使用re,多個分割符分割字元串及應用(萬能字元串時間轉時間格式)使用re,多個分割符分割字元串及應用(萬能字元串時間轉時間格式)

使用re,多個分割符分割字元串及應用(萬能字元串時間轉時間格式)

# 一個時間字元串
s = '2019-7-3 12:00:00'
'''介紹一個萬能的時間字元串轉時間的方法'''
from datetime import datetime
d = [int(item) for item in re.split('[- :]', s)]
res = datetime(*d)
res
           
datetime.datetime(2019, 7, 3, 12, 0)
           
2019-07-03 12:00:00
           

re.split()使用的時候注意’[- :]'不能以空格開頭

['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
           
['2019', '7', '3', '12', '00', '00']
           

re在字元串的處理上還有其他的比如格式化替換原則等,需要持續學習。