I have 2 dates in datetime format, one of them contains date, month and year and the second contains only month and date. ie----> 21 December 2019 and July 3.
Now I want to check if a date contains year or not. My code is as follows:
import datetime
x = datetime.datetime(2020, 5, 17)
if '%Y' in x:
print("contains year")
else:
print("doesn't contain year")
But I'm getting an error: TypeError: argument of type 'datetime.datetime' is not iterable
CodePudding user response:
If x is a datetime, it must be the year. But with the result of 3 December that I assume you actually mean string.
The best tool you can use in this situation is max
. Get the bigger number in x and check this is a year.
x = (2020, 5, 17)
max_record = max(x)
if max_record > 32: #Since we know that the month will be 12 and the day will be 31 at the most, numbers greater than 32 should be considered years.
print("X have a year.: " str(max_record))
else:
print("X don't have year.")
CodePudding user response:
Iteration is is basically repeating something and in CS usually applies to lists, arrays or other items you can count through. The error is caused by the fact that you are treating a datetime object like a list, and python isn't seeing a repeatable part of the value.
You maintain that you have more than one datetime object, and that one of them is missing the year. It is hard to see how that is possible, as you are required to supply all three: year, month and day; when you are creating that object.
With that said, we can attack the problem from two directions. First we can assume that everything works that we can check the datetime object for a valid date value. If something might be wrong with the date time object we can convert the object to a string and check the string for the required year info in multiple different ways. The following checks to see if the length is less than a full date time string, if there is a dash is the expected position, and if date is an unexpected default value.
import datetime
x = datetime.datetime(1900,12,2)
if x.year == 1900:
print("invalid date")
#assuming something might be wrong with the datetime object
#converting it to a string will let you examine the parts:
#string format of object: "1900-12-02 00:00:00"
d = str(x)
if len(d) < 19 or d[4:5] != "-" or d[0:4] == "1900":
print("invalid date")