在Python中从复杂字符串检索日期
我正在尝试使用datetime.strTime从两个字符串中获取一个datetime 时间非常简单(例如,晚上8:53),所以我可以做如下事情:在Python中从复杂字符串检索日期,python,string,datetime,strptime,Python,String,Datetime,Strptime,我正在尝试使用datetime.strTime从两个字符串中获取一个datetime 时间非常简单(例如,晚上8:53),所以我可以做如下事情: theTime = datetime.strptime(givenTime, "%I:%M%p") theDate = datetime.strptime(givenURL, "http://site.com/?year=%Y&month=%m&day=%d&hour=%H") 但是,字符串不仅仅是一个日期,它是一个类似于h
theTime = datetime.strptime(givenTime, "%I:%M%p")
theDate = datetime.strptime(givenURL, "http://site.com/?year=%Y&month=%m&day=%d&hour=%H")
但是,字符串不仅仅是一个日期,它是一个类似于http://site.com/?year=2011&month=10&day=5&hour=11
。我知道我可以这样做:
theTime = datetime.strptime(givenTime, "%I:%M%p")
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获取它,然后调用DateTime.replace(小时=小时,来自不同的源)
这样,您就不必进行任何额外的解析。如果您想简单地从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)
结果
givenURL == http://site.com/?year=2011&month=10&day=5&hour=11
givenTime == 08:53PM
map(int,regx.search(givenURL).groups()) == [2011, 10, 5]
theDate == 2011-10-05 <type 'datetime.date'>
theTime == 1900-01-01 20:53:00 <type 'datetime.datetime'>
theDateTime == 2011-10-05 20:53:00 <type 'datetime.datetime'>
0.460598763251 seconds eyquem's code
2011-10-05 08:53:00
2.10386180366 seconds Artsiom's code
2011-10-05 08:53:00
True
结果
givenURL == http://site.com/?year=2011&month=10&day=5&hour=11
givenTime == 08:53PM
map(int,regx.search(givenURL).groups()) == [2011, 10, 5]
theDate == 2011-10-05 <type 'datetime.date'>
theTime == 1900-01-01 20:53:00 <type 'datetime.datetime'>
theDateTime == 2011-10-05 20:53:00 <type 'datetime.datetime'>
0.460598763251 seconds eyquem's code
2011-10-05 08:53:00
2.10386180366 seconds Artsiom's code
2011-10-05 08:53:00
True
我的代码快了4.5倍。如果有很多这样的转换要执行,这可能会很有趣,非常令人印象深刻,但不幸的是,您的方法比其他方法更不清晰,因此,我的技能水平的人可能会在其中迷失一点。谢谢你的意见,这是一种非常酷的方式。