在 Python 中从复杂字符串中检索日期

2024-04-15

我正在尝试使用 datetime.strptime 从两个字符串中获取单个日期时间。

时间很容易(例如晚上 8:53),所以我可以做类似的事情:

theTime = datetime.strptime(givenTime, "%I:%M%p")

但是,该字符串不仅仅是一个日期,它是一个格式类似于以下内容的链接http://site.com/?year=2011&month=10&day=5&hour=11。我知道我可以做这样的事情:

theDate = datetime.strptime(givenURL, "http://site.com/?year=%Y&month=%m&day=%d&hour=%H")

但我不想从链接中获取该时间,因为它正在其他地方检索。有没有办法放置一个虚拟符号(例如%x或其他东西)作为最后一个变量的灵活空间?

最后,我设想有一行类似于:

theDateTime = datetime.strptime(givenURL + givenTime, ""http://site.com/?year=%Y&month=%m&day=%d&hour=%x%I:%M%p")

(尽管显然不会使用 %x)。有任何想法吗?


认为如果您想简单地从 URL 中跳过时间,您可以使用 split,例如以下方式:

givenURL = 'http://site.com/?year=2011&month=10&day=5&hour=11'
pattern = "http://site.com/?year=%Y&month=%m&day=%d"
theDate = datetime.strptime(givenURL.split('&hour=')[0], pattern)

所以不确定你是否正确理解,但是:

givenURL = 'http://site.com/?year=2011&month=10&day=5&hour=11'
datePattern = "http://site.com/?year=%Y&month=%m&day=%d"
timePattern = "&time=%I:%M%p"

theDateTime = datetime.strptime(givenURL.split('&hour=')[0] + '&time=' givenTime, datePattern + timePattern)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Python 中从复杂字符串中检索日期 的相关文章

随机推荐