我有一些日期,其中包含多天,我正试图分析。datetime.strptime函数似乎不支持正则表达式,因此我无法让它一次忽略一天。有什么简单的解决办法吗?我错过了?
下面是一些示例:
2011年3月20日至6月8日 2010年9月4日及27日 2013年2月15日、12月5日及6日
我知道这些例子中的每一个都有很大的不同,但我希望能找到其中一个的解决方案。使用一些格式化参数可以轻松地跨范围工作的方法将是非常棒的。
此外,在某些情况下,日期的格式可能会不同,我认为应该更容易处理:
2011年7月2日和2011年9月8日
发布于 2018-08-20 19:23:36
也许这不是最好的方法,但这是我的尝试:
import re
date1 = "March 20 & June 8, 2011"
date2 = "September 4 & 27, 2010"
date3 = "February 15, December 5 & 6, 2013"
date_group = [date1,date2,date3]
for date in date_group:
result = re.findall(r"\d{4}|[A-Z][a-z]+ \d{1,2} & \d{1,2}|[A-Z][a-z]+ \d{1,2}", date)
year = result[-1]
for i in range(len(result)-1):
d = result[i].split(" ")
try:
d.remove("&")
except ValueError:
pass
finally:
for a in range(1,len(d)):
date = d[0]+'{:02d}'.format(int(d[a]))+year
time_date = datetime.strptime(date,"%B%d%Y")
print (time_date)
结果:
2011-03-20 00:00:00
2011-06-08 00:00:00
2010-09-04 00:00:00
2010-09-27 00:00:00
2013-02-15 00:00:00
2013-12-05 00:00:00
2013-12-06 00:00:00
基本上先提取一年,然后再提取日期。不过,如果有几年的话,那就行不通了。
发布于 2018-08-20 22:38:10
这是一种使用datetime
模块的方法
演示:
import datetime
d1 = "March 20 & June 8, 2011"
d2 = "February 15, December 5 & 6, 2013"
def getDate(in_value):
result = []
in_value = in_value.split(",")
year = in_value.pop(-1)
for dateV in in_value:
if "&" in dateV:
temp = []
val = dateV.split()
month = val.pop(0)
for i in val:
if i.isdigit():
temp.append(datetime.datetime.strptime("{}-{}-{}".format(year, month, i).strip(), "%Y-%B-%d").strftime("%m/%d/%Y"))
result.append(" & ".join(temp))
else:
result.append(datetime.datetime.strptime(dateV.strip() + year, "%B %d %Y").strftime("%m/%d/%Y"))
return ", ".join(result)
print( getDate(d1) )
print( getDate(d2) )
输出:
03/20/2011 & 03/08/2011
02/15/2013, 12/05/2013 & 12/06/2013
发布于 2018-08-20 19:07:44
首先,将日期字符串拆分为有效日期:
import re
def split_date(d):
return re.split(‘[,|&]’, d)
https://stackoverflow.com/questions/51940862
复制