我有一個很長的字符串包含日期,並希望更新所有日期的格式。查找,重新格式化並替換字符串中的多個日期
以下是我與位的僞代碼我想不通一起寫入:
import datetime
current_date_format = "%d/%m/%Y"
new_date_format = "%d/%b/%Y"
def main():
line = "This is text dated 01/02/2017, and there are a few more dates such as 03/07/2017 and 09/06/2000"
print(line)
# Best way to pull out and replace all of the dates?
# pseudo:
for each current_date_format in line as date_in_line
temp_date = fix_date(date_in_line)
line.replace(date_in_line, temp_date)
print(line)
def fix_date(date_string=''):
return datetime.datetime.strptime(date_string, current_date_format).strftime(new_date_format)
在這種情況下,如果要打印:
This is text dated 01/02/2017, and there are a few more dates such as 03/07/2017 and 09/06/2000
This is text dated 01/FEB/2017, and there are a few more dates such as 03/JUL/2017 and 09/JUN/2000
感謝
您可以嘗試使用正則表達式來匹配'dd/mm/YYYY'和一個字典,以將數值'mm'值映射到相應的字符串表示形式。不過,您可能已在導入的'datetime'庫中找到了一些東西,或者可能會看看'pandas'。我已經完成了一些日期時間操作,如果你發現相關的東西,科學圖書館總是有很多支持。 編輯:請參閱https://stackoverflow.com/questions/3276180/extracting-date-from-a-string-in-python @unutbu在該帖子中發佈的帖子提及了可能對您有用的內容 –
謝謝@DarrelHolt我會看看'pandas'我在'datetime'和'dateutil'之間徘徊。但喜歡'datetime'的方式讓你建立自己的格式。 – Jake
我確實看到了這個問題,但不幸的是'dateutil.parser'只能處理一個日期的字符串。我的字符串將有0-n個日期。 – Jake