Select to view content in your preferred language

Error with Dates when Adding Features with Python API

262
3
02-27-2025 10:41 AM
mpboyle
Frequent Contributor

I'm getting the errors shown in the first screenshot below when trying to add features to a hosted feature layer using the Python API.

The features throwing the error all seem to have dates at or prior to 1/1/1900.

When constructing the JSON for the features to add, I'm assigning our local time zone to the datetime object.  Is there a different approach I should be taking to avoid these errors?  The second screenshot shows a sample of the dictionary key and value being used when trying to add features.

If I set any dates at or prior to the year 1900 to NoneType objects, the features are written to the hosted feature layer without errors.

mpboyle_0-1740680833659.png

'DateField': datetime.datetime(1900, 1, 1, 12, 0, tzinfo=tzlocal())

 

0 Kudos
3 Replies
CodyPatterson
MVP Regular Contributor

Hey @mpboyle 

Could try this function here to just return any date earlier than 1/1/1900 to None, as that's the normal null value in a DB for date columns:

from datetime import datetime

def safe_datetime(date):
    return date if date >= datetime(1900, 1, 1) else None

'DateField': safe_datetime(datetime(1899, 12, 31))

In this case DateField will be None.

I think just setting to None will be one of the best bets here.

Cody

0 Kudos
mpboyle
Frequent Contributor

I'm already handling the dates if they're prior to 1900 (code below).  I'm really wondering why I'm getting an error at all when trying to insert a feature with a date prior to 1900...are these dates not supported by the Python API?

def format_date(input_value):
    if isinstance(input_value, datetime.datetime):
        if input_value.year <= 1900:
            return None
        else:
            return input_value
    else:
        return None 

 

0 Kudos
JohnEvans6
Frequent Contributor

Came across this looking for something else doing something similar. I don't know if something that says "works on my machine" is helpful but everything seemed to upload for me doing the following:

timestamp_update.png

 

Maybe there's something up with tzlocal() not producing a timezone object?

 

0 Kudos