Example code
a = '27-10-80'
b = '27-10-22'
c = '27-10-50'
x = datetime.strptime(a, '%d-%m-%y')
print(x)
y = datetime.strptime(b, '%d-%m-%y')
print(y)
z = datetime.strptime(c, '%d-%m-%y')
print(z)
Output:
1980-10-27 00:00:00
2022-10-27 00:00:00
2050-10-27 00:00:00
How did datetime decide the year generated from string using '%y' format. Why did 80 become 1980 while 50 become 2050?
CodePudding user response:
The Python documentation indicates that strftime/strptime follows the semantics of C
Most of the functions defined in this module call platform C library functions with the same name.
as well as documents the behaviour of %y
:
Function strptime() can parse 2-digit years when given %y format code. When 2-digit years are parsed, they are converted according to the POSIX and ISO C standards: values 69–99 are mapped to 1969–1999, and values 0–68 are mapped to 2000–2068.
But we can confirm this behaviour by looking up STRPTIME(3), for %y
:
the year within the current century. When a century is not otherwise specified, values in the range 69-99 refer to years in the twentieth century (1969 to 1999 inclusive); values in the range 00-68 refer to years in the twenty-first century (2000 to 2068 inclusive). Leading zeros are permitted but not required.
emphasis mine.
There is no expressed reasoning for that cutoff, but it is reasonable to think that it stems from the UNIX EPOCH being 1970, with a year of safety margin at the boundary.
CodePudding user response:
This is documented under the comment section of _strptime.py
.
if group_key == 'y':
year = int(found_dict['y'])
# Open Group specification for strptime() states that a %y
#value in the range of [00, 68] is in the century 2000, while
#[69,99] is in the century 1900
if year <= 68:
year = 2000
else:
year = 1900
CodePudding user response:
From the documentation of time
Function strptime() can parse 2-digit years when given %y format code. When 2-digit years are parsed, they are converted according to the POSIX and ISO C standards: values 69–99 are mapped to 1969–1999, and values 0–68 are mapped to 2000–2068.