Created
March 7, 2020 17:43
-
-
Save crapher/8f180462d9e1290ec83f37b4ed146f7c to your computer and use it in GitHub Desktop.
Converting string date to python datetime
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
from datetime import date | |
# Months Dictionary | |
MONTHS = {'enero': 1, 'febrero': 2, 'marzo': 3, 'abril': 4, 'mayo': 5, 'junio': 6, 'julio': 7, 'agosto': 8, 'septiembre': 9, 'octubre': 10, 'noviembre': 11, 'diciembre': 12} | |
# Function that converts thex date to python datetime | |
def get_date_from_text(text): | |
# Remove spaces to simplify the RegEx | |
text = text.replace(' ', '') | |
# Find the pattern | |
# (\d{1,2}): search for one or two numeric characters (First group - This is the day) | |
# de: the word "de" | |
# (\w+): search a string (Second group - this is the month) | |
# del?: the word "de" or "del" (the letter l is optional) | |
# (\d{4}): search for four numeric characters (Third group - This is the year) | |
text = re.search('(\d{1,2})de(\w+)del?(\d{4})', text, re.IGNORECASE) | |
# Check if there are 3 group, if there are no 3 groups, there text is invalid | |
if len(text.groups()) != 3: | |
raise Exception('Incorrect Date Format') | |
day = int(text.group(1)) # Convert the first group to integer (Day) | |
year = int(text.group(3)) # Convert the third group to integer (Year) | |
month = MONTHS[text.group(2).lower()] # Map the month in words to the MONTHS dictionary (the dictionary key is the month in lowercase, the dictionary value is the month number) | |
return date(year, month, day) # Return the Python datetime | |
date_string = "7 de marzo de 2020" | |
python_date = get_date_from_text(date_string) | |
print(date_string, '-->', python_date) | |
date_string = "6 de agosto del 2005" | |
python_date = get_date_from_text(date_string) | |
print(date_string, '-->', python_date) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment