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.
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.
datetime.date.fromordinal(datetime.date.today().toordinal()-1)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With