Get yesterday's date in Python, DST-safe

python

Solution

datetime.date.fromordinal(datetime.date.today().toordinal()-1)

Problem

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.

Original source

Related problems