I have a birth date field like: date = '07-JUL-50'
and when I wanna get the year I got this:
my_date = datetime.datetime.strptime(date, "%d-%b-%y")
>>> my_date.year
2050
Is there an elegant way of get '1950'??
Thx
Documentation says that:
When 2-digit years are accepted, they are converted according to the POSIX or X/Open standard: values 69-99 are mapped to 1969-1999, and values 0–68 are mapped to 2000–2068.
That's why you are seeing 2050.
If you want 1950
instead, it depends on what are allowed dates in your particular scenario. E.g. if date values can be only dates in the past, you can do something like this:
import datetime
def get_year(date):
my_date = datetime.datetime.strptime(date, "%d-%b-%y")
now = datetime.datetime.now()
if my_date > now:
my_date = my_date.replace(year=my_date.year - 100)
return my_date.year
print get_year('07-JUL-50') # prints 1950
print get_year('07-JUL-13') # prints 2013
print get_year('07-JUL-14') # prints 1914
Hope that helps.