2015-02-11 51 views
3

我想生成一個隨機日期,並在該日期添加了一些日子,但我正面臨着這個錯誤。我想它與我的日期格式有關,但我找不到解決方案。未轉換的數據仍然是:15

我認爲這是因爲我需要兩位數字的日期和月份,這裏是我的代碼,它會產生一個錯誤。

start_day = randint(1,31) 
strt_day = [] 
strt_day.append("%02d" % start_day) 
start_day = strt_day 

strt_moth = [] 
start_month = randint(2,4) 
strt_moth.append("%02d" % start_month) 
start_month = strt_moth 

start_date = ""+start_month[0]+"/"+start_day[0]+"/2015" 
depart = datetime.datetime.strptime(start_date, "%m/%d/%y") 

關於我在做什麼的任何想法是錯誤的?

感謝

+1

因爲'%y'是一個**兩位數的年份**,例如'20' - >'2020'; '%Y'(注意!)是四位數字。但是,爲什麼你不使用'datetime.datetime(2015,randint(2,4),randint(1,31))'(請注意,並非所有月份的2月 - 4月都有31天...)? – jonrsharpe 2015-02-11 14:16:06

+1

混淆地將變量命名爲彼此的拼寫錯誤? – tripleee 2015-02-11 14:16:42

+0

@jonrsharpe謝謝!是的,你是對的,你看到的所有代碼只是我試圖找到錯誤。 – JordanBelf 2015-02-11 14:18:45

回答

4

因爲%y是一個兩位數的年份,所以2015被解釋爲20(即2020)和15剩下:

>>> import datetime 
>>> datetime.datetime.strptime("01/02/20", "%d/%m/%y") 
datetime.datetime(2020, 2, 1, 0, 0) 
>>> datetime.datetime.strptime("01/02/2015", "%d/%m/%y") 

Traceback (most recent call last): 
    File "<pyshell#1>", line 1, in <module> 
    datetime.datetime.strptime("01/02/2015", "%d/%m/%y") 
    File "C:\Python27\lib\_strptime.py", line 328, in _strptime 
    data_string[found.end():]) 
ValueError: unconverted data remains: 15 

你想%Y(注),這是一個四位數的年份:

>>> datetime.datetime.strptime("01/02/2015", "%d/%m/%Y") 
datetime.datetime(2015, 2, 1, 0, 0) 

您應該通讀the docs,其中解釋了各種格式指令。


但是,涉及串額外的步驟看似毫無意義,爲什麼不通過你創造datetime.datetime整數?

>>> import random 
>>> random.seed(0) 
>>> datetime.datetime(2015, random.randint(2, 4), random.randint(1, 31)) 
datetime.datetime(2015, 4, 24, 0, 0) 

注意,這可能會產生無效日期(例如月沒有30日!):

>>> random.seed(8) 
>>> datetime.datetime(2015, random.randint(2, 4), random.randint(1, 31)) 

Traceback (most recent call last): 
    File "<pyshell#28>", line 1, in <module> 
    datetime.datetime(2015, random.randint(2, 4), random.randint(1, 31)) 
ValueError: day is out of range for month 
相關問題