<p>可能有一条更简单的路线,但这是可行的(从您的一条线路):</p>
<pre><code>from time import strptime
text = "<H2>04018 BIKF Keflavikurflugvollur Observations at 00Z 26 Feb 1983</H2>"
text = text.replace("Z","").replace("</H2>","").split(" ")
text[-2]=str(strptime(text[-2],"%b").tm_mon)
text = "-".join(text[-4:])
</code></pre>
<p>提供:</p>
<pre><code>print(text)
> '00-26-2-1983'
</code></pre>
<hr/>
<p><strong>解释:</strong></p>
<p><code>text.replace("Z","")</code>删除文本中的“Z”(用空字符串“”替换“Z”)。<code>.replace("</H2>","")</code>进一步删除“”。<code>.split(" ")</code>将字符串更改为字符串列表。第三行返回:</p>
<pre><code>['<H2>04018', 'BIKF', 'Keflavikurflugvollur', 'Observations', 'at', '00', '26', 'Feb', '1983']
</code></pre>
<p>在这里,我们只需要将“Feb”(索引<code>-2</code>更改为一个用<code>strptime(text[-2],"%b").tm_mon</code>完成的数字,并用<code>str()</code>将其转换回一个字符串。第四行返回:</p>
<pre><code>['<H2>04018', 'BIKF', 'Keflavikurflugvollur', 'Observations', 'at', '00', '26', '2', '1983']
</code></pre>
<p>最后,感兴趣的字符串(从索引<code>-4</code>到结尾)可以根据您的请求用“-”连接起来,就像在最后一行<code>"-".join(text[-4:])</code>中所做的那样。你知道吗</p>
<hr/>
<p>另外,您已经尝试过的方法也存在一些问题<code>datetime_object = datetime.strptime('00Z 28 Feb 1983', '%h %d %M %Y')</code>。首先,strtime不知道它应该对“Z”做什么:在把它交给函数之前必须丢弃它。然后,您没有将正确的参数传递给函数。根据<a href="https://www.tutorialspoint.com/python/time_strptime.htm" rel="nofollow noreferrer">the tutorial</a>,以下是您告诉strtime的内容:</p>
<ul>
<li><code>%h</code>:与<code>%b</code>=缩写月名相同</li>
<li><code>%d</code>:每月的第几天(01到31)</li>
<li><code>%M</code>:分钟</li>
<li><code>%Y</code>:包括世纪在内的年份</li>
</ul>
<p>但这些并不是你实际赋予函数的内容:“00 28 Feb 1983”实际上是:</p>
<ul>
<li><code>%H</code>:小时,使用24小时制(00到23)</li>
<li><code>%d</code>:月日(01到31)(这个是正确的)</li>
<li><code>%b</code>:缩写月份名称</li>
<li><code>%Y</code>:年份包括世纪(这个是正确的)</li>
</ul>
<p>解决这个问题,你会得到:</p>
<pre><code>datetime_object = datetime.strptime('00 28 Feb 1983', '%H %d %b %Y')
> time.struct_time(tm_year=1983, tm_mon=2, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=59, tm_isdst=-1)
</code></pre>
<p>您可以从中获得:</p>
<pre><code>text = str(datetime_object.tm_hour)+"-"+str(datetime_object.tm_mday)+"-"+str(datetime_object.tm_mon)+"-"+str(datetime_object.tm_year)
> '0-28-2-1983'
</code></pre>