Search code examples
pythondatetimevalueerror

ValueError: time data '' does not match format '%Y-%m-%d %H:%M'


I'm new to coding and cant figure out where i'm breaking. The ValueError keeps coming up but i cant seem to figure out where i'm breaking

def sunset(date,daycycle):

    sunset_date_time = ''
    year = date.strftime("%Y")
    year_data = daycycle.get(year)

    if(year_data != None):
        month_day = date.strftime("%m-%d")

        result_set = year_data.get(month_day)
    
        if(result_set != None):
            sunset_time = result_set["sunset"]
            sunset_date_time = year + "-" + month_day + " " + sunset_time

   return datetime.datetime.strptime(sunset_date_time, "%Y-%m-%d %H:%M")

Solution

  • This error is caused by the date format of the variable "sunset_date_time"

    When you try to return the object this variable not have the date format as "%Y-%m-%d %H:%M"

    To see what format have you can try print this value or return from the function and check the order of year, month, day , hour and minutes

    def sunset(date,daycycle):

    sunset_date_time = ''
    year = date.strftime("%Y")
    year_data = daycycle.get(year)
    
    if(year_data != None):
        month_day = date.strftime("%m-%d")
    
        result_set = year_data.get(month_day)
    
        if(result_set != None):
            sunset_time = result_set["sunset"]
            sunset_date_time = year + "-" + month_day + " " + sunset_time 
    print(sunset_date_time)
    """
    or return sunset_date_time
    """