![](/img/trans.png)
[英]How Do You Scrape (with Python) a Website That Is Not Formatted Like A Table?
[英]How do you add : to a time formatted like this 203045 in python?
我一直試圖在python中將此時間格式的值從203045更改為20:40:45。 我顯然不知道從哪里開始。 任何幫助將不勝感激! 謝謝!
使用datetime
strptime
和strftime
函數,前者從字符串構造一個datetime對象,后者將datetime對象格式化為具有特定格式的字符串:
from datetime import datetime
datetime.strptime("203045", "%H%M%S").strftime("%H:%M:%S")
# '20:30:45'
您還可以使用正則表達式獲得相同的結果:)
import re
ch = "203045"
print ":".join(re.findall('\d{2}',ch))
# '20:30:45'
嘗試此操作以刪除最后兩個數字(如果它們等於零):
import re
ch = "20304500"
print ":".join([e for e in re.findall('\d{2}',ch) if e!="00"])
# '20:30:45'
或其他任何數字(最后兩位):
import re
ch = "20304500"
print ":".join(re.findall('\d{2}',ch)[:-1])
# '20:30:45'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.