Get yesterday's date in Python, DST-safe

前端 未结 3 443
粉色の甜心
粉色の甜心 2020-12-05 13:37

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 m

相关标签:
3条回答
  • 2020-12-05 14:21

    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.

    0 讨论(0)
  • 2020-12-05 14:27

    You'll get 2013-03-10 if you use naive datetime object that knows nothing about timezones (and DST in particular):

    from datetime import datetime, timedelta
    
    dt_naive = datetime(2013, 3, 11, 0, 35)
    print((dt_naive - timedelta(days=1)).date()) # ignores DST
    # -> 2013-03-10
    

    2013-03-09 is correct if you are interested what date it was 24 hours ago.

    import pytz # $ pip install pytz
    
    local_tz = pytz.timezone("America/Chicago") # specify your local timezone
    dt = local_tz.localize(dt_naive, is_dst=None) # raise if dt_naive is ambiguous
    yesterday = local_tz.normalize(dt - timedelta(days=1)).date()
    print(yesterday)
    # -> 2013-03-09
    

    Note: .date() strips timezone info so you'll get 2013-03-10 again:

    print(dt.date() - timedelta(days=1))
    # -> 2013-03-10
    

    To get yesterday in particular timezone:

    from datetime import datetime, time, timedelta
    import pytz # $ pip install pytz
    
    tz = pytz.timezone("America/Chicago")
    yesterday = datetime.now(tz).date() - timedelta(days=1)
    
    # to add timezone info back (to get yesterday's midnight)
    midnight = tz.localize(datetime.combine(yesterday, time(0, 0)), is_dst=None)
    

    Getting yesterday by stripping timezone info might fail if the timezone has missing days around that time. Then this method would produce non-existing date in the given timezone (tz.localize() raises an error).

    0 讨论(0)
  • 2020-12-05 14:37
    datetime.date.fromordinal(datetime.date.today().toordinal()-1)
    
    0 讨论(0)
提交回复
热议问题