Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get yesterday's date in Python, DST-safe

Tags:

I have a python script that uses this call to get yesterday's date in YYYY-MM-DD format:

str(date.today() - timedelta(days=1))) 

It works most of the time, but when the script ran this morning at 2013-03-11 0:35 CDT it returned "2013-03-09" instead of "2013-03-10".

Presumably daylight saving time (which started yesterday) is to blame. I guess the way timedelta(days=1) is implemented it subtracted 24 hours, and 24 hours before 2013-03-11 0:35 CDT was 2013-03-09 23:35 CST, which led to the result of "2013-03-09".

So what's a good DST-safe way to get yesterday's date in python?

UPDATE: After bukzor pointed out that my code should have worked properly, I went back to the script and determined it wasn't being used. It sets the default value, but a wrapper shell script was setting the date explicitly. So the bug is in the shell script, not the python script.

like image 949
Ike Walker Avatar asked Mar 11 '13 17:03

Ike Walker


People also ask

How do I find yesterday'S date?

How do you get yesterdays' date using JavaScript? We use the setDate() method on yesterday , passing as parameter the current day minus one. Even if it's day 1 of the month, JavaScript is logical enough and it will point to the last day of the previous month.


2 Answers

datetime.date.fromordinal(datetime.date.today().toordinal()-1) 
like image 179
Robᵩ Avatar answered Oct 18 '22 08:10

Robᵩ


I'm not able to reproduce your issue in python2.7 or python3.2:

>>> import datetime >>> today = datetime.date(2013, 3, 11) >>> print today 2013-03-11 >>> day = datetime.timedelta(days=1) >>> print today - day 2013-03-10 

It seems to me that this is already the simplest implementation of a "daylight-savings safe" yesterday() function.

like image 36
bukzor Avatar answered Oct 18 '22 07:10

bukzor