【问题标题】:Adding days to a date in Python在 Python 中将日期添加到日期
【发布时间】:2011-10-15 19:23:09
【问题描述】:

我有一个日期"10/10/11(m-d-y)",我想使用 Python 脚本为其添加 5 天。请考虑一个适用于月底的通用解决方案。

我正在使用以下代码:

import re
from datetime import datetime

StartDate = "10/10/11"

Date = datetime.strptime(StartDate, "%m/%d/%y")

print Date -> 正在打印'2011-10-10 00:00:00'

现在我想在这个日期上增加 5 天。我使用了以下代码:

EndDate = Date.today()+timedelta(days=10)

返回此错误:

name 'timedelta' is not defined

【问题讨论】:

标签: python date datetime timedelta


【解决方案1】:

前面的答案是正确的,但通常这样做是更好的做法:

import datetime

然后你就会有,使用datetime.timedelta:

date_1 = datetime.datetime.strptime(start_date, "%m/%d/%y")

end_date = date_1 + datetime.timedelta(days=10)

【讨论】:

  • datetime.datetime - 为什么两次?
  • 像“from datetime import datetime, timedelta”这样的导入会增加代码的可读性
  • @paulmorriss:你是在datetime模块的datetime类上调用strptime方法,所以你需要指定datetime.datetime
  • 我们是否都同意将常用的类命名为与包含它的模块相同的名称是一个愚蠢的想法? datetime 是什么?您不能依赖约定来知道,但总是必须查看导入。
  • 那里有长尾遗留问题。它“应该”是from datetime import DateTime,因为类是 CamelCased,但日期时间在 PEP8 之前。
【解决方案2】:

首先导入timedeltadate

from datetime import timedelta, date

date.today() 将返回今天的日期时间,可能是你想要的

EndDate = date.today() + timedelta(days=10)

【讨论】:

  • datetime.date.today() 而不是 Date.today()
  • @dan-klasson 它对我不起作用,date 对象没有 timedelta 方法。你用的是什么 Python 版本?
  • @DrTyrsa 我的错。应该是:from datetime import timedelta, date; date.today() + timedelta(days=10)
  • 我使用的是 python 3.7。为我工作。非常感谢。
【解决方案3】:

如果你碰巧已经在使用pandas,你可以不指定格式来节省一点空间:

import pandas as pd
startdate = "10/10/2011"
enddate = pd.to_datetime(startdate) + pd.DateOffset(days=5)

【讨论】:

  • 对我来说效果很好。谢谢
  • 只想指出,仅仅为此安装 pandas 实在是太过分了。
  • 这对我来说是最好的答案,因为我已经在使用 pandas 并且不想再导入另一个库。
【解决方案4】:

如果您想现在添加日期,可以使用此代码

from datetime import datetime
from datetime import timedelta


date_now_more_5_days = (datetime.now() + timedelta(days=5) ).strftime('%Y-%m-%d')

【讨论】:

    【解决方案5】:

    这可能会有所帮助:

    from datetime import date, timedelta
    date1 = date(2011, 10, 10)
    date2 = date1 + timedelta(days=5)
    print (date2)
    

    【讨论】:

    • 有个小错字,第三行应该是 date2 = date1 + timedelta(days=5)
    【解决方案6】:

    这是另一种使用 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(days=5)
    print 'After 5 Days:', date_after_month.strftime('%d/%m/%Y %H:%M:%S')
    

    输出:

    今天:25/06/2015 15:56:09

    5 天后:30/06/2015 15:56:09

    【讨论】:

    • relativedelta 在对月年等进行操作时特别有用。
    【解决方案7】:

    我猜你错过了类似的东西:

    from datetime import timedelta
    

    【讨论】:

      【解决方案8】:

      这是一个从现在开始 + 指定天数的函数

      import datetime
      
      def get_date(dateFormat="%d-%m-%Y", addDays=0):
      
          timeNow = datetime.datetime.now()
          if (addDays!=0):
              anotherTime = timeNow + datetime.timedelta(days=addDays)
          else:
              anotherTime = timeNow
      
          return anotherTime.strftime(dateFormat)
      

      用法:

      addDays = 3 #days
      output_format = '%d-%m-%Y'
      output = get_date(output_format, addDays)
      print output
      

      【讨论】:

      • 好代码。但是您的 IF 不需要在 get_date 中测试 addDays
      【解决方案9】:

      为了有一个冗长的代码,并避免名称冲突 datetime 和 datetime.datetime,你应该重命名类CamelCase 名称。

      from datetime import datetime as DateTime, timedelta as TimeDelta
      

      所以你可以做以下,我认为它更清楚。

      date_1 = DateTime.today() 
      end_date = date_1 + TimeDelta(days=10)
      

      此外,如果您以后想import datetime,也不会有名称冲突

      【讨论】:

        【解决方案10】:

        试试这个:

        在当前日期加上 5 天。

        from datetime import datetime, timedelta
        
        current_date = datetime.now()
        end_date = current_date + timedelta(days=5) # Adding 5 days.
        end_date_formatted = end_date.strftime('%Y-%m-%d')
        print(end_date_formatted)
        

        从当前日期减去 5 天。

        from datetime import datetime, timedelta
        
        current_date = datetime.now()
        end_date = current_date + timedelta(days=-5) # Subtracting 5 days.
        end_date_formatted = end_date.strftime('%Y-%m-%d')
        print(end_date_formatted)
        

        【讨论】:

          【解决方案11】:

          使用timedeltas 你可以这样做:

          import datetime
          today=datetime.date.today()
          
          
          time=datetime.time()
          print("today :",today)
          
          # One day different .
          five_day=datetime.timedelta(days=5)
          print("one day :",five_day)
          #output - 1 day , 00:00:00
          
          
          # five day extend .
          fitfthday=today+five_day
          print("fitfthday",fitfthday)
          
          
          # five day extend .
          fitfthday=today+five_day
          print("fitfthday",fitfthday)
          #output - 
          today : 2019-05-29
          one day : 5 days, 0:00:00
          fitfthday 2019-06-03
          

          【讨论】:

            【解决方案12】:

            通常您现在已经有了答案,但也许我创建的课程也会有所帮助。对我来说,它解决了我在 Pyhon 项目中的所有要求。

            class GetDate:
                def __init__(self, date, format="%Y-%m-%d"):
                    self.tz = pytz.timezone("Europe/Warsaw")
            
                    if isinstance(date, str):
                        date = datetime.strptime(date, format)
            
                    self.date = date.astimezone(self.tz)
            
                def time_delta_days(self, days):
                    return self.date + timedelta(days=days)
            
                def time_delta_hours(self, hours):
                    return self.date + timedelta(hours=hours)
            
                def time_delta_seconds(self, seconds):
                    return self.date + timedelta(seconds=seconds)
            
                def get_minimum_time(self):
                    return datetime.combine(self.date, time.min).astimezone(self.tz)
            
                def get_maximum_time(self):
                    return datetime.combine(self.date, time.max).astimezone(self.tz)
            
                def get_month_first_day(self):
                    return datetime(self.date.year, self.date.month, 1).astimezone(self.tz)
            
                def current(self):
                    return self.date
            
                def get_month_last_day(self):
                    lastDay = calendar.monthrange(self.date.year, self.date.month)[1]
                    date = datetime(self.date.year, self.date.month, lastDay)
                    return datetime.combine(date, time.max).astimezone(self.tz)
            

            如何使用

            1. self.tz = pytz.timezone("Europe/Warsaw") - 在这里定义你想在项目中使用的时区
            2. GetDate("2019-08-08").current() - 这会将您的字符串日期转换为具有您在 pt 1 中定义的时区的时间感知对象。默认字符串格式为format="%Y-%m-%d",但您可以随意更改它。 (例如GetDate("2019-08-08 08:45", format="%Y-%m-%d %H:%M").current()
            3. GetDate("2019-08-08").get_month_first_day() 返回给定日期(字符串或对象)月份的第一天
            4. GetDate("2019-08-08").get_month_last_day() 返回给定日期月份的最后一天
            5. GetDate("2019-08-08").minimum_time() 返回给定日期开始日期
            6. GetDate("2019-08-08").maximum_time() 返回给定日期的结束日期
            7. GetDate("2019-08-08").time_delta_days({number_of_days}) 返回给定日期 + 添加 {天数}(您也可以致电:GetDate(timezone.now()).time_delta_days(-1) 表示昨天)
            8. GetDate("2019-08-08").time_delta_haours({number_of_hours}) 类似于 pt 7,但按小时工作
            9. GetDate("2019-08-08").time_delta_seconds({number_of_seconds}) 与 pt 7 类似,但在几秒钟内工作

            【讨论】:

              【解决方案13】:

              有时我们需要使用从日期到日期进行搜索。如果我们使用date__range,那么我们需要在to_date 中添加1 天,否则查询集将为空。

              例子:

              from datetime import timedelta  
              
              from_date  = parse_date(request.POST['from_date'])
              
              to_date    = parse_date(request.POST['to_date']) + timedelta(days=1)
              
              attendance_list = models.DailyAttendance.objects.filter(attdate__range = [from_date, to_date])
              

              【讨论】:

                【解决方案14】:

                我已经看到了一个 pandas 示例,但这里有一个转折点,您可以直接导入 Day 类

                from pandas.tseries.offsets import Day
                
                date1 = datetime(2011, 10, 10)
                date2 = date1 + 5 * Day()
                

                【讨论】:

                  【解决方案15】:
                  class myDate:
                  
                      def __init__(self):
                          self.day = 0
                          self.month = 0
                          self.year = 0
                          ## for checking valid days month and year
                          while (True):
                              d = int(input("Enter The day :- "))
                              if (d > 31):
                                  print("Plz 1 To 30 value Enter ........")
                              else:
                                  self.day = d
                                  break
                  
                          while (True):
                              m = int(input("Enter The Month :- "))
                              if (m > 13):
                                  print("Plz 1 To 12 value Enter ........")
                              else:
                                  self.month = m
                                  break
                  
                          while (True):
                              y = int(input("Enter The Year :- "))
                              if (y > 9999 and y < 0000):
                                  print("Plz 0000 To 9999 value Enter ........")
                              else:
                                  self.year = y
                                  break
                      ## method for aday ands cnttract days
                      def adayDays(self, n):
                          ## aday days to date day
                          nd = self.day + n
                          print(nd)
                          ## check days subtract from date
                          if nd == 0: ## check if days are 7  subtracted from 7 then,........
                              if(self.year % 4 == 0):
                                  if(self.month == 3):
                                      self.day = 29
                                      self.month -= 1
                                      self.year = self. year
                              else:
                                  if(self.month == 3):
                                      self.day = 28
                                      self.month -= 1
                                      self.year = self. year
                              if  (self.month == 5) or (self.month == 7) or (self.month == 8) or (self.month == 10) or (self.month == 12):
                                  self.day = 30
                                  self.month -= 1
                                  self.year = self. year
                                     
                              elif (self.month == 2) or (self.month == 4) or (self.month == 6) or (self.month == 9) or (self.month == 11):
                                  self.day = 31
                                  self.month -= 1
                                  self.year = self. year
                  
                              elif(self.month == 1):
                                  self.month = 12
                                  self.year -= 1    
                          ## nd == 0 if condition over
                          ## after subtract days to day io goes into negative then
                          elif nd < 0 :   
                              n = abs(n)## return positive if no is negative
                              for i in range (n,0,-1): ## 
                                  
                                  if self.day == 0:
                  
                                      if self.month == 1:
                                          self.day = 30
                                          
                                          self.month = 12
                                          self.year -= 1
                                      else:
                                          self.month -= 1
                                          if(self.month == 1) or (self.month == 3)or (self.month == 5) or (self.month == 7) or (self.month == 8) or (self.month == 10) or (self.month ==12):
                                              self.day = 30
                                          elif(self.month == 4)or (self.month == 6) or (self.month == 9) or (self.month == 11):
                                              self.day = 29
                                          elif(self.month == 2):
                                              if(self.year % 4 == 0):
                                                  self.day == 28
                                              else:
                                                  self.day == 27
                                  else:
                                      self.day -= 1
                  
                          ## enf of elif negative days
                          ## adaying days to DATE
                          else:
                              cnt = 0
                              while (True):
                  
                                  if self.month == 2:  # check leap year
                                      
                                      if(self.year % 4 == 0):
                                          if(nd > 29):
                                              cnt = nd - 29
                                              nd = cnt
                                              self.month += 1
                                          else:
                                              self.day = nd
                                              break
                                  ## if not leap year then
                                      else:  
                                      
                                          if(nd > 28):
                                              cnt = nd - 28
                                              nd = cnt
                                              self.month += 1
                                          else:
                                              self.day = nd
                                              break
                                  ## checking month other than february month
                                  elif(self.month == 1) or (self.month == 3) or (self.month == 5) or (self.month == 7) or (self.month == 8) or (self.month == 10) or (self.month == 12):
                                      if(nd > 31):
                                          cnt = nd - 31
                                          nd = cnt
                  
                                          if(self.month == 12):
                                              self.month = 1
                                              self.year += 1
                                          else:
                                              self.month += 1
                                      else:
                                          self.day = nd
                                          break
                  
                                  elif(self.month == 4) or (self.month == 6) or (self.month == 9) or (self.month == 11):
                                      if(nd > 30):
                                          cnt = nd - 30
                                          nd = cnt
                                          self.month += 1
                  
                                      else:
                                          self.day = nd
                                          break
                                  ## end of month condition
                          ## end of while loop
                      ## end of else condition for adaying days
                      def formatDate(self,frmt):
                  
                          if(frmt == 1):
                              ff=str(self.day)+"-"+str(self.month)+"-"+str(self.year)
                          elif(frmt == 2):
                              ff=str(self.month)+"-"+str(self.day)+"-"+str(self.year)
                          elif(frmt == 3):
                              ff =str(self.year),"-",str(self.month),"-",str(self.day)
                          elif(frmt == 0):
                              print("Thanky You.....................")
                              
                          else:
                              print("Enter Correct Choice.......")
                          print(ff)
                              
                              
                  
                  dt = myDate()
                  nday = int(input("Enter No. For Aday or SUBTRACT Days :: "))
                  dt.adayDays(nday)
                  print("1 : day-month-year")
                  print("2 : month-day-year")
                  print("3 : year-month-day")
                  print("0 : EXIT")
                  frmt = int (input("Enter Your Choice :: "))
                  dt.formatDate(frmt)
                  

                  【讨论】:

                    猜你喜欢
                    • 2010-11-28
                    • 1970-01-01
                    • 2023-03-08
                    • 1970-01-01
                    • 2010-10-08
                    • 1970-01-01
                    • 2012-08-18
                    相关资源
                    最近更新 更多