Cannot Unpack Non-iterable Nonetype Objects in Python

This Python code creates a datetime object using a list of values representing year, month, day, hour, and minute. By unpacking the list with the * operator, the datetime.datetime() function is provided with the required arguments. The resulting date and time is printed in the format “YYYY-MM-DD HH:MM

Code with Original Error:

codetime_list = [2020, 3, 23, 7, 30]
import datetime
time = datetime.datetime(*time_list)
print(time)

# Traceback (most recent call last):
# File "PycharmProjects\\hello world\\app.py", line 4, in <module>
# datetime.datetime()
# TypeError: function missing required argument 'year' (pos 1)
# 2020-02-25 00:00:00
#
# Process finished with exit code

It seems like there’s a small mistake in how you’re passing the time_list into datetime.datetime(). The correct way to do this would be to pass the list as arguments using unpacking (with the * operator). However, it looks like you might have included an incorrect argument or missing a month/day value. Let me show you the corrected version of your code and explain it below:

Corrected Code:

codeimport datetime

time_list = [2020, 2, 25, 7, 30] # Adjusted month and day
time = datetime.datetime(*time_list)
print(time)

In the fixed code:

  • I’ve adjusted the time_list to [2020, 2, 25, 7, 30]. The second element should represent the month (2 for February), and the third represents the day (25).
  • The *time_list unpacks the list and passes the elements as arguments to datetime.datetime().

Result:

This should print the correct date and time:

code2020-02-25 07:30:00

Blog Post Example:

Understanding and Fixing Python datetime Errors: A Quick Guide

In Python, working with dates and times using the datetime module can sometimes lead to confusing errors. A common mistake occurs when attempting to create a datetime object from a list of values. If you’re passing a list to datetime.datetime(), the list must contain all the required arguments in the correct order: year, month, day, hour, minute, and so on.

Consider the following example:

codeimport datetime

time_list = [2020, 3, 23, 7, 30] # Year, Month, Day, Hour, Minute
time = datetime.datetime(*time_list)
print(time)

This code should create a datetime object for March 23, 2020, at 7:30 AM. However, if you accidentally pass incorrect values or omit an essential part (such as month or day), Python will throw a TypeError.

Here’s what a common error might look like:

codeTypeError: function missing required argument 'year' (pos 1)

Resolving the Error

To resolve this, ensure that your list contains all the required arguments in the correct order. If the error persists, carefully check the list elements to ensure they match the format required by datetime.datetime().

Once you’ve corrected the list, your code should run without issues, producing the expected output. If you’re passing a list, remember to use the * operator to unpack it.

Related blog posts