簡體   English   中英

在python中添加時間添加功能

[英]Making a time adding function in python

我正在嘗試構建一個可以接收日期並添加日期的函數,以在萬一發生更改時更新所有內容,到目前為止,我已經提出了以下建議:

def addnewDate(date, numberOfDays):

    date = date.split(":")   
    day = int(date[0])
    month = int(date[1])
    year = int(date[2])
    new_days = 0
    l = 0
    l1 = 28
    l2 = 30
    l3 = 31
    #l's are the accordingly days of the month

    while numberOfDays > l:
        numberOfDays  = numberOfDays - l 
        if month != 12:
            month += 1
        else:
            month = 1
            year += 1

        if month in [1, 3, 5, 7, 8, 10, 12]:
            l = l3
        elif month in [4, 6, 9, 11]:
            l = l2
        else:
            l = l1

    return  str(day) + ':' + str(month) + ':' + str(year) #i'll deal 
    #with fact that it doesn't put the 0's in the < 10 digits later

所需的輸出:

addnewDate('29:12:2016', 5):

'03:01:2017'

我認為問題出在變量或者我在其中使用它們的位置,雖然有點失落。

提前致謝!

PS我不能使用python內置函數:)

由於您無法使用標准庫,因此這是我的嘗試。 我希望我不要忘記任何事情。

  • 定義月份長度表
  • 如果檢測到leap年則進行調整(每隔4年,但有特殊情況)
  • 在零索引的日期和月份工作,更加容易
  • 添加天數。 如果小於當前月份的天數,則結束,否則減去當前月份的天數並重試( while循環)
  • 當上個月到達時,增加年份
  • 最后在日期和月份中加1

碼:

def addnewDate(date, numberOfDays):
    month_days = [31,28,31,30,31,30,31,31,30,31,30,31]

    date = date.split(":")
    day = int(date[0])-1
    month = int(date[1])-1
    year = int(date[2])
    if year%4==0 and year%400!=0:
        month_days[1]+=1

    new_days = 0
    #l's are the accordingly days of the month

    day += numberOfDays

    nb_days_month = month_days[month]

    done = False   # since you don't want to use break, let's create a flag
    while not done:
        nb_days_month = month_days[month]
        if day < nb_days_month:
            done = True
        else:
            day -= nb_days_month
            month += 1
            if month==12:
                year += 1
                month = 0


return  "{:02}:{:02}:{:04}".format(day+1,month+1,year)

測試(可能並不詳盡):

for i in ("28:02:2000","28:02:2004","28:02:2005","31:12:2012","03:02:2015"):
    print(addnewDate(i,2))
    print(addnewDate(i,31))

結果:

02:03:2000
31:03:2000
01:03:2004
30:03:2004
02:03:2005
31:03:2005
02:01:2013
31:01:2013
05:02:2015
06:03:2015

當然,這只是為了好玩。 其他使用timedatetime time模塊!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM