How can I create a template from this template?

I need to use datetime.strptime for text that looks like this.

"Some random texts of indefinite length January 28, 1986

how to do it?

+3
source share
3 answers

Using the final 3 words, there is no need for regular expressions (using the time module):

 >>> import time >>> a="Some Random text of undetermined length Jan 28, 1986" >>> datetuple = a.rsplit(" ",3)[-3:] >>> datetuple ['Jan', '28,', '1986'] >>> time.strptime(' '.join(datetuple),"%b %d, %Y") time.struct_time(tm_year=1986, tm_mon=1, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=28, tm_isdst=-1) >>> 

Using the datetime module:

 >>> from datetime import datetime >>> datetime.strptime(" ".join(datetuple), "%b %d, %Y") datetime.datetime(1986, 1, 28, 0, 0) >>> 
+2
source

You can find this helpful question. I will give the answer that I gave there that the dateutil module should use. This takes a fuzzy parameter that will ignore any text that doesn't look like a date. i.e:

 >>> from dateutil.parser import parse >>> parse("Some Random text of undetermined length Jan 28, 1986", fuzzy=True) datetime.datetime(1986, 1, 28, 0, 0) 
+4
source

Do not try to use strptime to write non-date text. For a good match, fuzzy dateutil.parser is fine, but if you know the date format, you can use a regular expression to search for a date in a string, and then use strptime to turn it into a datetime object, for example:

 import datetime import re pattern = "((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [0-9]+, [0-9]+)" datestr = re.search(, s).group(0) d = datetime.datetime.strptime(datestr, "%b %d, %Y") 
+3
source

All Articles