如何将日期时间增加一天?

Pol*_*Pol 126 python datetime

如何增加日期时间?

for i in range(1, 35)
    date = datetime.datetime(2003, 8, i)
    print(date)
Run Code Online (Sandbox Code Playgroud)

但我需要正确地经历数月和数年?有任何想法吗?

unu*_*tbu 216

date = datetime.datetime(2003,8,1,12,4,5)
for i in range(5): 
    date += datetime.timedelta(days=1)
    print(date) 
Run Code Online (Sandbox Code Playgroud)

  • 如果你需要考虑夏令时; 它更复杂,例如,参见[如何从python日期减去一天?](http://stackoverflow.com/a/25427822/4279) (7认同)
  • 就像一个魅力...即使是06/30. (7认同)

Pio*_*uda 49

使用timedelta对象可以完成递增日期:

import datetime

datetime.datetime.now() + datetime.timedelta(days=1)
Run Code Online (Sandbox Code Playgroud)

在Python文档中查找timedelta对象:http://docs.python.org/library/datetime.html


小智 11

最简单的解决方案

from datetime import timedelta, datetime
date = datetime(2003,8,1,12,4,5)
for i in range(5):
    date += timedelta(days=1)
    print(date)
Run Code Online (Sandbox Code Playgroud)


Atu*_*ind 10

这是使用dateutil的relativedelta在日期上添加天数的另一种方法.

from datetime import datetime
from dateutil.relativedelta import relativedelta

print 'Today: ',datetime.now().strftime('%d/%m/%Y %H:%M:%S') 
date_after_month = datetime.now()+ relativedelta(day=1)
print 'After a Days:', date_after_month.strftime('%d/%m/%Y %H:%M:%S')
Run Code Online (Sandbox Code Playgroud)

输出:

今天:25/06/2015 20:41:44

一天之后:2015年6月1日20:41:44

  • @JFSebastian只是为了分享另一种可能的方式来添加一天. (2认同)
  • 如果没有优势,我认为它不会增加价值。 (2认同)

Mar*_*oma 8

在某些情况下,所有当前答案都是错误的,因为他们不认为时区会改变相对于UTC的偏移量.因此,在某些情况下,添加24小时与添加日历日不同.

提出的解决方案

以下解决方案适用于萨摩亚并保持当地时间不变.

def add_day(today):
    """
    Add a day to the current day.

    This takes care of historic offset changes and DST.

    Parameters
    ----------
    today : timezone-aware datetime object

    Returns
    -------
    tomorrow : timezone-aware datetime object
    """
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    tomorrow_utc_tz = tomorrow_utc_tz.replace(hour=today.hour,
                                              minute=today.minute,
                                              second=today.second)
    return tomorrow_utc_tz
Run Code Online (Sandbox Code Playgroud)

经过测试的代码

# core modules
import datetime

# 3rd party modules
import pytz


# add_day methods
def add_day(today):
    """
    Add a day to the current day.

    This takes care of historic offset changes and DST.

    Parameters
    ----------
    today : timezone-aware datetime object

    Returns
    -------
    tomorrow : timezone-aware datetime object
    """
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    tomorrow_utc_tz = tomorrow_utc_tz.replace(hour=today.hour,
                                              minute=today.minute,
                                              second=today.second)
    return tomorrow_utc_tz


def add_day_datetime_timedelta_conversion(today):
    # Correct for Samoa, but dst shift
    today_utc = today.astimezone(datetime.timezone.utc)
    tz = today.tzinfo
    tomorrow_utc = today_utc + datetime.timedelta(days=1)
    tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
    return tomorrow_utc_tz


def add_day_dateutil_relativedelta(today):
    # WRONG!
    from dateutil.relativedelta import relativedelta
    return today + relativedelta(days=1)


def add_day_datetime_timedelta(today):
    # WRONG!
    return today + datetime.timedelta(days=1)


# Test cases
def test_samoa(add_day):
    """
    Test if add_day properly increases the calendar day for Samoa.

    Due to economic considerations, Samoa went from 2011-12-30 10:00-11:00
    to 2011-12-30 10:00+13:00. Hence the country skipped 2011-12-30 in its
    local time.

    See https://stackoverflow.com/q/52084423/562769

    A common wrong result here is 2011-12-30T23:59:00-10:00. This date never
    happened in Samoa.
    """
    tz = pytz.timezone('Pacific/Apia')
    today_utc = datetime.datetime(2011, 12, 30, 9, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2011-12-29T23:59:00-10:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2011-12-31T23:59:00+14:00'


def test_dst(add_day):
    """Test if add_day properly increases the calendar day if DST happens."""
    tz = pytz.timezone('Europe/Berlin')
    today_utc = datetime.datetime(2018, 3, 25, 0, 59,
                                  tzinfo=datetime.timezone.utc)
    today_tz = today_utc.astimezone(tz)  # 2018-03-25T01:59:00+01:00
    tomorrow = add_day(today_tz)
    return tomorrow.isoformat() == '2018-03-26T01:59:00+02:00'


to_test = [(add_day_dateutil_relativedelta, 'relativedelta'),
           (add_day_datetime_timedelta, 'timedelta'),
           (add_day_datetime_timedelta_conversion, 'timedelta+conversion'),
           (add_day, 'timedelta+conversion+dst')]
print('{:<25}: {:>5} {:>5}'.format('Method', 'Samoa', 'DST'))
for method, name in to_test:
    print('{:<25}: {:>5} {:>5}'
          .format(name,
                  test_samoa(method),
                  test_dst(method)))
Run Code Online (Sandbox Code Playgroud)

检测结果

Method                   : Samoa   DST
relativedelta            :     0     0
timedelta                :     0     0
timedelta+conversion     :     1     0
timedelta+conversion+dst :     1     1
Run Code Online (Sandbox Code Playgroud)

  • 其他答案并非完全错误,它们在使用 UTC 或 naive (`tzinfo == None`) 日期时间时完全没问题。 (2认同)

Aus*_*_10 5

这对我来说是一个简单的解决方案:

from datetime import timedelta, datetime

today = datetime.today().strftime("%Y-%m-%d")
tomorrow = datetime.today() + timedelta(1)

Run Code Online (Sandbox Code Playgroud)