2

The date in my data does not come in one single format. It comes as "yyyy", "mm/dd/yyyy" and "Jun-03". I want to extract the year out of it.

0

2 Answers 2

8

Using dateutil:

In [24]: import dateutil.parser as parser

In [28]: parser.parse('Jun-03').year  # assumes the current year
Out[28]: 2013

In [29]: parser.parse('08/09/2012').year
Out[29]: 2012

In [30]: parser.parse('2012').year
Out[30]: 2012
Sign up to request clarification or add additional context in comments.

4 Comments

I have installed the python-dateutil(2.1 version) but it would throw No module found. >>> import dateutil Traceback (most recent call last): File "<pyshell#101>", line 1, in <module> import dateutil ImportError: No module named dateutil
How did you install python-dateutil? The message ImportError: No module named dateutil indicates it was not successfully installed.
Downloaded the tar.zip file, unzipped it and from the command prompt went into the folder and typed 'python setup.py install' . I can see "python_dateutil-2.1-py2.7.egg" folder only in the site packages
@mickey To install the package go to Scripts folder under Python folder and run the following: C:\Python27\Scripts>pip install python-dateutil
3

If you can assume that the year is always 4 digits except when the current year is implied, you can use a simple regular expression:

match = re.search('\d{4}', date)
year = match.group(0) if match else '2013'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.