Search code examples
pythondatetimestrftime

How to format '0000-00-00 00:00:00' using strftime() in python?


formatting date as:

dob = datetime(0000, 00, 00)
dob = dob.strftime("%Y-%m-%d")

but it gives error: ValueError: year is out of range

how can i format datetime(0000,00,00) using strftime() in python?


Solution

  • Python's documentation on the datetime module, particularly the datetime class states that the datetime object can have attribute values in the following range:

    MINYEAR <= year <= MAXYEAR
    1 <= month <= 12
    1 <= day <= number of days in the given month and year
    0 <= hour < 24
    0 <= minute < 60
    0 <= second < 60
    0 <= microsecond < 1000000
    

    This module also defines the following constants:

    datetime.MINYEAR
    

    The smallest year number allowed in a date or datetime object. MINYEAR is 1.

    datetime.MAXYEAR
    

    The largest year number allowed in a date or datetime object. MAXYEAR is 9999.

    which means that you cannot use those (datetime(0000, 00, 00)) parameters in the constructor of the datetime class, hence the ValueError stating that the given year is out of range

    Since you can't construct a datetime object with the following arguments in the first place, there is no way to call the strftime method on it.