Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Get Yesterday's date as a string in YYYY-MM-DD format

As an input to an API request I need to get yesterday's date as a string in the format YYYY-MM-DD. I have a working version which is:

yesterday = datetime.date.fromordinal(datetime.date.today().toordinal()-1) report_date = str(yesterday.year) + \    ('-' if len(str(yesterday.month)) == 2 else '-0') + str(yesterday.month) + \    ('-' if len(str(yesterday.day)) == 2 else '-0') + str(yesterday.day) 

There must be a more elegant way to do this, interested for educational purposes as much as anything else!

like image 470
Jacob Avatar asked May 27 '15 13:05

Jacob


People also ask

How do I return yesterday's date in Python?

You just have to subtract no. of days using 'timedelta' that you want to get back in order to get the date from the past. For example, on subtracting two we will get the date of the day before yesterday.

How do I convert a date to a string in Python?

To convert Python datetime to string, use the strftime() function. The strftime() method is a built-in Python method that returns the string representing date and time using date, time, or datetime object.


1 Answers

You Just need to subtract one day from today's date. In Python datetime.timedelta object lets you create specific spans of time as a timedelta object.

datetime.timedelta(1) gives you the duration of "one day" and is subtractable from a datetime object. After you subtracted the objects you can use datetime.strftime in order to convert the result --which is a date object-- to string format based on your format of choice:

>>> from datetime import datetime, timedelta >>> yesterday = datetime.now() - timedelta(1)  >>> type(yesterday)                                                                                                                                                                                     >>> datetime.datetime      >>> datetime.strftime(yesterday, '%Y-%m-%d') '2015-05-26' 

Note that instead of calling the datetime.strftime function, you can also directly use strftime method of datetime objects:

>>> (datetime.now() - timedelta(1)).strftime('%Y-%m-%d') '2015-05-26' 

As a function:

def yesterday(string=False, frmt='%Y-%m-%d'):     yesterday = datetime.now() - timedelta(1)     if string:         return yesterday.strftime(frmt)     return yesterday 
like image 153
Mazdak Avatar answered Sep 18 '22 18:09

Mazdak