Piyush Patil
Piyush Patil

Reputation: 14543

How to get date range for one day using strftime?

I am pulling data from a third party api where we have to provide a date range for the data. Below is how to apply the date range I am confused in how i do the startDate so it is yesterdays date?

params = {
        "queryId": query_id,
        "startDate": "2020-01-01",
        "endDate": datetime.strftime(datetime.today(), "%Y-%m-%d"),
        "pageSize": "5000"
    }

I want the startdate to be set to yesterday's date.

Upvotes: 0

Views: 412

Answers (3)

BlackList96
BlackList96

Reputation: 449

You can use timedelta object to solve this problem.

From python's official documentation,

Description

A timedelta object represents a duration, the difference between two dates or times.

Syntax

class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

So, You can use timedelta object to represent 1 day and then subtract it from the current day to get the date of yesterday. The solution will be as follows,


from datetime import datetime, timedelta  # Make sure to import timedelta

params = {
        "queryId": query_id,
        "startDate": datetime.strftime(datetime.today() - timedelta(days=1), "%Y-%m-%d"),
        "endDate": datetime.strftime(datetime.today(), "%Y-%m-%d"),
        "pageSize": "5000"
    }
  • More about timedelta here.

Upvotes: 1

azro
azro

Reputation: 54168

You need datetime.timedelta

from datetime import datetime, timedelta

today = datetime.today().strftime("%Y-%m-%d")
print(today)     # 2020-08-13

yesterday = (datetime.today() - timedelta(days=1)).strftime("%Y-%m-%d")
print(yesterday) # 2020-08-12

The possibilities with timedelta are

timedelta(days=1)
timedelta(seconds=1)
timedelta(microseconds=1)
timedelta(milliseconds=1)
timedelta(minutes=1)
timedelta(hours=1)
timedelta(weeks=1)

Upvotes: 2

Cory Kramer
Cory Kramer

Reputation: 118001

If "endDate" is today

datetime.today()

then yesterday can just be one day less than that

datetime.today() - timedelta(days=1)

You can obviously pass this into datetime.strftime for "startDate" the same way you do for "endDate"

Upvotes: 0

Related Questions