Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dateutil.parser.parse is parsing '0001' as 2001. How can i solve this to read it as 0001 only

from datetime import datetime
import dateutil.parser

date = '0001-01-01T00:00:00+02:00'
parsed_date = dateutil.parser.parse(date)
year = parsed_date.year
print(year)
>>> 2001

Desired Output: 0001

Any Idea???

like image 542
user3235267 Avatar asked Jun 17 '15 14:06

user3235267


People also ask

What is Dateutil parser in Python?

This module offers a generic date/time string parser which is able to parse most known formats to represent a date and/or time. This module attempts to be forgiving with regards to unlikely input formats, returning a datetime object even for dates which are ambiguous.


1 Answers

When calling dateutil.parser.parse, you can also specify a parameter "parseinfo" (see here). This is an object which defines certain behaviour when parsing the date, including how the date is handled. It has a "convertyear" method.

By overriding that method, you can change the default behaviour (which is documented here) to achieve what you're trying to do. Here's a slightly changed version of your code using this object:

from datetime import datetime
import dateutil.parser

class NoYearHandlingParserInfo(dateutil.parser.parserinfo):
     def convertyear(self, year):
         return int(year)

date = '0001-01-01T00:00:00+02:00'
parsed_date = dateutil.parser.parse(date, parserinfo=NoYearHandlingParserInfo())
year = parsed_date.year
print(year)

which gives the correct output of "1". If you really need the literal 0001, you can pad that integer like so:

print('{:04d}'.format(year))
like image 75
wonderb0lt Avatar answered Sep 22 '22 17:09

wonderb0lt