Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract date from string in python

How can I extract "20151101" (as string) from "Campaign on 01.11.2015"?

I have read this one: Extracting date from a string in Python . But I am getting stuck when converting from Match object to string.

like image 779
Vũ Nam Hưng Avatar asked Aug 18 '26 18:08

Vũ Nam Hưng


2 Answers

With minor tweaks in the aforementioned post, you can get it to work.

import re
from datetime import datetime

text = "Campaign on 01.11.2015"

match = re.search(r'\d{2}.\d{2}.\d{4}', text)
date = datetime.strptime(match.group(), '%d.%m.%Y').date()
print str(date).replace("-", "")
20151101
like image 164
Nickil Maveli Avatar answered Aug 20 '26 12:08

Nickil Maveli


Here is one way, using re.sub():

import re

s = "Campaign on 01.11.2015"

new_s = re.sub(r"Campaign on (\d+)\.(\d+)\.(\d+)", r'\3\2\1', s)

print new_s

And another, using re.match():

import re

s = "Campaign on 01.11.2015"

match = re.match(r"Campaign on (\d+)\.(\d+)\.(\d+)", s)
new_s = match.group(3)+match.group(2)+match.group(1)

print new_s
like image 33
Robᵩ Avatar answered Aug 20 '26 14:08

Robᵩ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!