从Python中复杂的字符串检索日期 [英] Retrieving a date from a complex string in Python

查看:188
本文介绍了从Python中复杂的字符串检索日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to get a single datetime out of two strings using datetime.strptime.

时间很简单(例如下午8:53),所以我可以做一些像:

The time is pretty easy (ex. 8:53PM), so I can do something like:

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

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

However, the string has more than just a date, it's a link in a format similar to http://site.com/?year=2011&month=10&day=5&hour=11. I know that I could do something like:

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

但是我不希望从链接中获取那个小时,因为它被其他地方检索。有没有办法把一个虚拟符号(比如%x或某些东西)作为最后一个变量的灵活空间?

but I don't want to get that hour from the link since it's being retrieved elsewhere. Is there a way to put a dummy symbol (like %x or something) to serve as a flexible space for that last variable?

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

In the end, I envision having a single line similar to:

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

(虽然显然,%x不会被使用)任何想法?

(although, obviously, the %x wouldn't be used). Any ideas?

推荐答案

想想,如果你想从URL简单的跳过时间,你可以使用split例如以下方式:

Think that if you would like to simple skip time from the URL you can use split for example the following way:

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)

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

So not sure that understood you correctly, but:

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中复杂的字符串检索日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆