519

日付が"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
4

15 に答える 15

778

前の答えは正しいですが、一般的には次のことを行う方が良い方法です。

import datetime

次に、を使用して、次のようになりますdatetime.timedelta

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

end_date = date_1 + datetime.timedelta(days=10)
于 2011-07-29T10:03:46.803 に答える
166

インポートtimedeltaしてdate最初に。

from datetime import timedelta, date

そしてdate.today()、今日の日時に戻ります、あなたが望むかもしれません

EndDate = date.today() + timedelta(days=10)
于 2011-07-29T09:20:23.267 に答える
33

すでにパンダを使用している場合は、形式を指定しないことで少しスペースを節約できます。

import pandas as pd
startdate = "10/10/2011"
enddate = pd.to_datetime(startdate) + pd.DateOffset(days=5)
于 2014-08-29T14:10:19.030 に答える
18

これは役立つかもしれません:

from datetime import date, timedelta
date1 = date(2011, 10, 10)
date2 = date1 + timedelta(days=5)
print (date2)
于 2020-10-01T12:07:00.483 に答える
16

今までの日数を追加したい場合は、このコードを使用できます

from datetime import datetime
from datetime import timedelta


date_now_more_5_days = (datetime.now() + timedelta(days=5) ).strftime('%Y-%m-%d')
于 2018-02-20T19:51:33.627 に答える
14

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

出力:

今日:2015年6月25日15:56:09

5日後:2015年6月30日15:56:09

于 2015-06-25T12:56:53.503 に答える
13

私はあなたがそのような何かを逃していると思います:

from datetime import timedelta
于 2011-07-29T09:20:48.633 に答える
9

これが今から+指定された日から取得する関数です

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
于 2014-11-14T08:01:56.787 に答える
7

コードの冗長性を減らし、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は発生しません。

于 2017-09-27T10:42:31.367 に答える
2

これを試して:

現在の日付に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)
于 2021-03-22T19:24:04.353 に答える
0

を使用してtimedelta行うことができます:

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
于 2019-05-29T07:02:22.753 に答える
0

一般的に、あなたは今答えを得ていますが、多分私が作成した私のクラスも役立つでしょう。私にとって、それは私の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に似ていますが、秒単位で動作します
于 2019-08-23T13:22:50.703 に答える
0

日付と日付による検索を使用する必要がある場合があります。を使用する場合はdate__range、に1日を追加する必要to_dateがあります。そうしないと、クエリセットが空になります。

例:

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])
于 2019-10-28T10:56:20.507 に答える
0

パンダの例はすでに見ましたが、ここでは、Dayクラスを直接インポートできるようにひねりを加えています

from pandas.tseries.offsets import Day

date1 = datetime(2011, 10, 10)
date2 = date1 + 5 * Day()
于 2021-03-19T12:54:57.540 に答える
-12
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)
于 2021-06-15T13:20:26.933 に答える