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???
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With