简体   繁体   中英

How to format a date value for Hubspot API using Python

I have read the docs saying that to pass the value for a Hubspot date field you should format your Date as midnight UTC. However, I've had no luck doing so in Python. I assume I am just missing the magic Python incantation that will get the right result. Here is what I have:

    from pytz import timezone, utc
    from hubspot.crm.contacts import SimplePublicObject,

    created_dt = # datetime from sqlalchemy query
    utcdt = utc.localize(
        datetime(
            year=created_dt.year,
            month=created_dt.month,
            day=created_dt.day
            )
    )
    ts = int(utcdt.timestamp())
    props = SimplePublicObjectInput({"last_booking": str(ts)})
    return client.crm.companies.basic_api.update(
        hs_id, simple_public_object_input=props
    )

this returns this error:

{"status":"error",
 "message":"Property values were not valid: [{\"isValid\":false,\"message\":\"1570233600 is at 4:10:33.600 UTC, not midnight!\"...
 }

Ah, the answer was right there. Python timestamp returns the time in seconds, and HubSpot expects microseconds. I just had to multiply by 1000:

ts = int(utcdt.timestamp()*1000)

now all looks good.

did you try adding hours and minutes to your datetime call

datetime(
    year=created_dt.year,
    month=created_dt.month,
    day=created_dt.day,
    hour=0,
    minute=0
)

Use the Hubspot supported "sanetime" module: https://github.com/HubSpot/sanetime

Then to get a date:

yourdate = datetime.datetime.date()
hubspot_date = sanetime.time(yourdate )

Or if you do not want a dependency:

#convert datetime to UTC
your_utc_datetime = your_datetime.astimezone(pytz.UTC)

#replace time with midnight
your_utc_date_midnight = your_utc_datetime.replace(hour=0,minute=0,second=0, microsecond=0)

# convert to epoch (Python 3.3+)
your_hubspot_date = your_utc_date_midnight.timestamp()*1000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM