Search code examples
pythondatetimeformatsendgrid-api-v3

Datetime library in Python giving incorrect format for YYYY-MM-DD resulting in error after embedding in API call


im new to python and trying to work with the Sendgrid api and the datetime library:

To try and pull email statistics my code is:

import http.client

conn = http.client.HTTPSConnection("api.sendgrid.com")

payload = "{}"

headers = { 'authorization': "Bearer SG.***" }

conn.request("GET", "/v3/stats?aggregated_by=day&start_date=2020-01-14", payload, headers)

res = conn.getresponse()
data = res.read()

print(data.decode("utf-8"))

This code works and I receive my desired output, however, I want to create this app such that it runs everyday through task scheduler and generates a report without nme manually changing the start date.

I tried:

from datetime import date
today = date.today()

if i print(today) it gives me the exact format 20120-01-14 but if i directly call today it says

today
Out[37]: datetime.date(2020, 1, 14)

Below I tried to put "today" as my start date but got the error of format

import http.client

conn = http.client.HTTPSConnection("api.sendgrid.com")

payload = "{}"

headers = { 'authorization': "Bearer SG.***" }

conn.request("GET", "/v3/stats?aggregated_by=day&start_date=today", payload, headers)

res = conn.getresponse()
data = res.read()

print(data.decode("utf-8"))

However, this gives me an error : {"errors":[{"message":"start_date is required and should be a YYYY-MM-DD formatted date"}]}

What can I do to put in the start_date in order for it to pickup the current date always without me manually changing it?


Solution

  • Try this:

    date.today().strftime('%Y-%m-%d')
    

    And change this line from this:

    conn.request("GET", "/v3/stats?aggregated_by=day&start_date=today", payload, headers)
    

    to this:

    conn.request("GET", "/v3/stats?aggregated_by=day&start_date={}".format(today), payload, headers)
    

    And take a look over python built-in date functions