【发布时间】:2017-12-22 14:25:10
【问题描述】:
我有一个包含日期的长字符串,想更新所有日期的格式。
以下是我写的以及我无法弄清楚的伪代码:
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。我已经对此进行了一些日期时间操作,如果您发现相关内容,科学图书馆总是会提供很多支持。编辑:见stackoverflow.com/questions/3276180/…@unutbu 在该线程上的帖子提到了一些可能对你有用的东西 -
谢谢@DarrelHolt 我会看看
pandas我在datetime和dateutil之间折腾。但喜欢datetime让你构建自己的格式的方式。 -
我确实看到了这个问题,但不幸的是
dateutil.parser只能处理一个日期的字符串。我的字符串将有 0-n 个日期。
标签: python