Python Forum
datetime.date() - TypeError: an integer is required (got type str)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
datetime.date() - TypeError: an integer is required (got type str)
#1
If I just want to print out the last day of every month from 2014 through 2017 I can do that no problem with the following code:

import arcpy
import datetime 
from datetime import timedelta
import time

def last_day_of_month(any_day):
    next_month = any_day.replace(day=28) + datetime.timedelta(days=4)
    return next_month - datetime.timedelta(days=next_month.day)
for year in range(2014,2018):
    for month in range(1, 13):
        print (last_day_of_month(datetime.date(year, month, 1))) 
But when I try and use it in an "if" statement then it wants me to turn "month" from a string into an integer
Error:
TypeError: an integer is required (got type str)
.



Here is the "if" statement:

if last_day_of_month(datetime.date(year, month, 1)) >= row[3].date():
                            arcpy.FeatureClassToFeatureClass_conversion(inFeatures, outLocation, outFeatureClass, expression)





Why does it not care that "month" is a string in the "print" statement, but it does with the "if" statement?
Reply
#2
what is your question? This snippet works for me.
Reply
#3
@buran I have updated my question. Thanks for the advice. I'm new to the forum
Reply
#4
Please, post the full traceback, not just the last line as well as the full code snippet
Reply
#5
Full Code:
import arcpy
import datetime 
from datetime import timedelta
import time
import calendar
from calendar import monthrange

#Document Start Time in-order to calculate Run Time
time1 = time.clock()

# Set environment settings
arcpy.env.workspace = r"C:\arcGIS_Shared\Python\CenterHeatMaps.gdb"

#Declare variables
fc = 'Open_GoHealth_Centers'
fields = ['USER_market_id','USER_GoHealth_ID','USER_GoHealth_Center_Name', 'USER_Opening_Date']
fieldname = 'USER_market_id'

#Define WHERE clause statement
whereclause = """{} = 2000""".format(arcpy.AddFieldDelimiters(fc, fieldname))
sqlclause = (None, 'Order By USER_market_id, USER_GoHealth_ID')

# loop through months
years = [2014, 2015, 2016, 2017]
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']


#returns last day of each month
def last_day_of_month(any_day):
    next_month = any_day.replace(day=28) + datetime.timedelta(days=4)
    return next_month - datetime.timedelta(days=next_month.day)
for year in range(2014,2018):
    for month in range(1, 13):
        #print (last_day_of_month(datetime.date(year, month, 1)))

        for year in years:
            for month in months:
                with arcpy.da.SearchCursor(in_table = fc, field_names = fields, where_clause=whereclause, sql_clause=(None, 'ORDER BY USER_market_id, USER_GoHealth_ID')) as cursor:
            #Loop through each row established in cursor
                    for row in (cursor):
                # Set local variables for FeatureClasstoFeatureClass
                        inFeatures = "PatientVisitsGeocoded"
                        outLocation = r"C:\arcGIS_Shared\Python\CenterHeatMaps.gdb"
                        outFeatureClass = "Date{2}{3}_NWPatientVisits{0}{1}".format(row[0], row[2], month, year)
                        delimitedfield = arcpy.AddFieldDelimiters(arcpy.env.workspace,"USER_CenterID")

                        expression = """{0} = {1} AND USER_DOSMonth = '{2}' AND USER_DOSYear = {3}""".format(delimitedfield, row[1], month, year)
                
    
#               Execute FeatureClassToFeatureClass
                        if last_day_of_month(datetime.date(year, month, 1)) >= row[3].date():
                            arcpy.FeatureClassToFeatureClass_conversion(inFeatures, outLocation, outFeatureClass, expression)
    
                #Print Results
                            print(row[2])
                            count = arcpy.GetMessageCount()
                            print (arcpy.GetMessage(count-1)) 
    
#Document End Time
time2 = time.clock()

#Run Time in seconds
runtime = (time2-time1)

print (str(timedelta(seconds=runtime))) 

Full Traceback:
Error:
runfile('C:/arcGIS_Shared/PythonScripts/CenterHeatMapScripts/Step2_FeatureClasstoFeatureClass_Test3.py', wdir='C:/arcGIS_Shared/PythonScripts/CenterHeatMapScripts') Traceback (most recent call last): File "<ipython-input-13-2d2db8c7b0f6>", line 1, in <module> runfile('C:/arcGIS_Shared/PythonScripts/CenterHeatMapScripts/Step2_FeatureClasstoFeatureClass_Test3.py', wdir='C:/arcGIS_Shared/PythonScripts/CenterHeatMapScripts') File "C:\Users\mazemar\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile execfile(filename, namespace) File "C:\Users\mazemar\AppData\Local\Continuum\anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/arcGIS_Shared/PythonScripts/CenterHeatMapScripts/Step2_FeatureClasstoFeatureClass_Test3.py", line 74, in <module> if last_day_of_month(datetime.date(year, month, 1)) >= row[3].date(): TypeError: an integer is required (got type str)
Reply
#6
well, you have line33 where you iterate over months as integers from range(1,13), but after that you have line37 where you use variable month to iterate over list months. all elements in list months are str, what you expect to happen? :-) Of course it will raise TypeError...
Actually you iterate 4*12 times over elements of years list and months list because of lines 32-33
Fix lines 32-37
Reply
#7
Thanks @buran. I was able to fix it by replacing the month abbreviations in the "months" list with their number identifiers (1-12)
Reply
#8
(Jan-30-2018, 07:26 PM)bisoftware Wrote: I was able to fix it by replacing the month abbreviations in the "months" list with their number identifiers (1-12)
you don't need to nest year and months loops twice. (lines 32-33 and lines 36-37).. fix this, one pair is enough, now you repeat the same checks 48 times.

see what you have now

years = [2014, 2015, 2016, 2017]
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
for year in range(2014,2018):
    for month in range(1, 13):
        #print (last_day_of_month(datetime.date(year, month, 1)))
        for year in years:
            for month in months:
                print(year, month)
and the output is

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Compare current date on calendar with date format file name Fioravanti 1 214 Mar-26-2024, 08:23 AM
Last Post: Pedroski55
  Python date format changes to date & time 1418 4 587 Jan-20-2024, 04:45 AM
Last Post: 1418
  TypeError: a bytes-like object is required ZeroX 13 4,087 Jan-07-2023, 07:02 PM
Last Post: deanhystad
  Review my code: convert a HTTP date header to a datetime object stevendaprano 1 1,986 Dec-17-2022, 12:24 AM
Last Post: snippsat
  "SUMIF" type query in Python (help required) BlainEillimatta 0 851 Oct-06-2022, 09:08 AM
Last Post: BlainEillimatta
  TypeError: a bytes-like object is required, not 'str' - Help Please. IanJ 3 4,796 Aug-29-2022, 05:53 PM
Last Post: deanhystad
  TypeError: unsupported operand type(s) for +: 'dict' and 'int' nick12341234 1 9,300 Jul-15-2022, 04:04 AM
Last Post: ndc85430
  TypeError: unsupported opperand type(s) for %: 'int' and 'list' cool_person 7 2,142 May-07-2022, 08:40 AM
Last Post: ibreeden
  TypeError: missing a required argument: 'y' gible 0 2,904 Dec-15-2021, 02:21 AM
Last Post: gible
  Filter dataframe by datetime.date column glidecode 2 5,107 Dec-05-2021, 12:51 AM
Last Post: glidecode

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020