Python datetime subtracting date oddity
Question: I have a datetime object created from which I subtract 13 days as follow:

    
    
    (date.today()-timedelta(days=13)).strftime('%Y-%m-%d')
    

The strangeness occurs when I execute the code at 6AM and 8:30AM. At 6AM, the
resulting string is returned as (if today is 2012-02-29):

2012-02-15

which is 14 days before the current! However, running the same line at 8:30AM,
the resulting string is returned as:

2012-02-16

Which then correct. So far I have not been able to figure out what the
difference is between the small period of time. I use timezone naive datetime
objects, if that is important. I would like to know what could cause this
change in the resulting string date.

Many thanks.

**EDIT: (based on eumiro's suggestion below)**

datetime.datetime.now() returns:

    
    
    >>> datetime.datetime(2012, 2, 29, 10, 46, 20, 659862) 
    

And the timezone is Europe/Vienna on the server and in the django application
that runs the line of code.

I also tried running a similar line to the one you suggested:

    
    
    (pytz.timezone(settings.TIME_ZONE).localize(datetime.now(), is_dst=True) - \
        timedelta(days=13)).strftime('%Y-%m-%d') 
    

But with the same results... which is why I think I don't think it has much to
do with timezones also. But at the same time not sure where else to look.


Answer: You live somewhere in America? This is the place where the timezones are
around 6-8 hours behind the UTC and that's the time of UTC midnight.

What does `datetime.datetime.now()` return?

If you want to get the real local time, use this (replace `"America/New_York"`
with your timezone):

    
    
    from datetime import datetime, timedelta
    import pytz
    
    now = datetime.datetime.now(pytz.timezone("America/New_York"))
    dt = (now - timedelta(days=13)).strftime('%Y-%m-%d')
    

and it should return the same correct values from midnight until midnight.

