gpt4 book ai didi

python - 从 Python 中的复杂字符串中检索日期

转载 作者:行者123 更新时间:2023-11-28 16:51:18 24 4
gpt4 key购买 nike

我正在尝试使用 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)

关于python - 从 Python 中的复杂字符串中检索日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7070175/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com