因为%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
因为'%y'是一个**两位数的年份**,例如'20' - >'2020'; '%Y'(注意!)是四位数字。但是,为什么你不使用'datetime.datetime(2015,randint(2,4),randint(1,31))'(请注意,并非所有月份的2月 - 4月都有31天...)? – jonrsharpe 2015-02-11 14:16:06
混淆地将变量命名为彼此的拼写错误? – tripleee 2015-02-11 14:16:42
@jonrsharpe谢谢!是的,你是对的,你看到的所有代码只是我试图找到错误。 – JordanBelf 2015-02-11 14:18:45