Because %y
is for a two-digit year, so 2015
is interpreted as 20
(i.e. 2020
) and the 15
is left over:
>>> 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
You want %Y
(note case!), which is a four-digit year:
>>> datetime.datetime.strptime("01/02/2015", "%d/%m/%Y")
datetime.datetime(2015, 2, 1, 0, 0)
You should read through the docs, which explain the various format directives.
However, the extra steps involving strings seem pointless, why not just pass the integers you create to 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)
Note that this might generate invalid dates (e.g. February doesn't have a 30th!):
>>> 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