我需要解析一些大致格式为(1或2位数字的年份)-(月缩写)的日期,例如:
5月5日(2005年6月)
1月13日(2013年1月)
我尝试使用格式为%b-%y
的strptime,但是它不能始终产生所需的日期。根据{{3}},这是因为我的数据集中的某些年份未填充零。
此外,当我在字符串“ 5-Jun”上测试日期时间模块(请参见下面的代码)时,得到的是“ 2019-06-05”,而不是预期的结果(2005年6月),即使我在致电yearfirst=True
时设置了parse
。
from dateutil.parser import parse
parsed = parse("5-Jun",yearfirst=True)
print(parsed)
答案 0 :(得分:1)
如果将0填充为一位数字年份,会更容易,因为可以使用格式将其直接转换为时间。这里使用正则表达式将单个数字实例替换为“ 0填充在前面”值。我使用了here中的正则表达式。
示例代码:
import re
match_condn = r'\b([0-9])\b'
replace_str = r'0\1'
datetime.strptime(re.sub(match_condn, replace_str, '15-Jun'), '%y-%b').strftime("%B %Y")
输出:
June 2015
答案 1 :(得分:0)
一种方法是使用str.zfill
例如:
import datetime
d = ["5-Jun", "13-Jan"]
for date in d:
date, month = date.split("-")
date = date.zfill(2)
print(datetime.datetime.strptime(date+"-"+month, "%y-%b").strftime("%B %Y"))
输出:
June 2005
January 2013
答案 2 :(得分:-1)
啊。我从@Rakesh的答案中看到了您的数据是关于什么的。我以为您需要解析月份的全名。因此,您有两个术语%b和%y向后,但随后出现了个位数年份的问题。我明白了如果可以假设您的日期始终是您指定的两种格式之一,那么这是一种获取所需内容的简单得多的方法:
inp = "5-Jun"
t = time.strptime(("0" + inp)[-6:], "%y-%b")