在Python中向日期添加天数



我有一个日期"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

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

import datetime

然后使用datetime.timedelta:

date_1 = datetime.datetime.strptime(start_date, "%m/%d/%y")
end_date = date_1 + datetime.timedelta(days=10)

先导入timedeltadate

from datetime import timedelta, date

date.today()将返回今天的日期时间,然后你可以添加一个timedelta到它:

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

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

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

这可能有帮助:

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

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

from datetime import datetime
from datetime import timedelta

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

下面是另一个使用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

我想你错过了这样的东西:

from datetime import timedelta

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

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

为了有一个更少的详细代码,并避免名称冲突之间的日期时间和日期时间。日期时间,您应该使用CamelCase名称重命名类。

from datetime import datetime as DateTime, timedelta as TimeDelta

所以你可以这样做,我认为这样更清楚。

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

另外,如果您稍后想要import datetime,则将没有名称冲突

试试这个:

当前日期增加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)

我刚刚看到了这个老帖子:

我检查过了,但大多数答案都是一样的。我喜欢两个答案,所以我想检查这两种方法的效率。

第一种方法:使用DateTime模块第二种方法:使用熊猫的图书馆

所以我运行了大约10k次测试,pandas库方法要慢得多。所以我建议使用内置的DateTime模块。

from datetime import date, timedelta
import pandas as pd
import timeit
def using_datetime():
    pre_date = date(2013, 10, 10)
    day_date = pre_date + timedelta(days=5)
    return day_date
def using_pd():
    start_date = "10/10/2022"
    pd_date = pd.to_datetime(start_date)
    end_date = pd_date + pd.DateOffset(days=5)
    return end_date
    
for func in [using_datetime, using_pd]:
    print(f"{func.__name__} Time Took: ",  timeit.timeit(stmt=func, number=10000))
    
# Output 
# using_datetime Time Took:  0.009390000021085143
# using_pd Time Took:  2.1051381999859586

使用 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

一般来说你现在已经得到了答案,但也许我创建的类也会有所帮助。对我来说,它解决了我在python项目中遇到的所有需求。

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,但工作在秒

有时我们需要使用from date &到目前为止。如果我们使用date__range,那么我们需要在to_date上添加1天,否则queryset将为空。

的例子:

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])

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

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

你可以这样使用它,它将工作:

如果只需要日期,则:

import datetime
StartDate = "10/10/11"
Date = datetime.datetime.strptime(StartDate, "%m/%d/%y").date()
print("Date: ", Date)
EndDate = Date + datetime.timedelta(days=10)
print("EndDate: ", EndDate)

如果同时需要日期和时间,则:

import datetime
StartDate = "10/10/11"
Date = datetime.datetime.strptime(StartDate, "%m/%d/%y")
print("Date: ", Date)
EndDate = Date + datetime.timedelta(days=10)
print("EndDate: ", EndDate)

忘记从datetime导入timedelta函数

修复方法如下:

import re
from datetime import datetime, timedelta
StartDate = "10/10/11"
Date = datetime.strptime(StartDate, "%m/%d/%y")
EndDate = Date.today()+timedelta(days=10)
print(EndDate)
这是上面代码的输出:2012-08-03 23:13:53.485750
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)

相关内容

  • 没有找到相关文章

最新更新