If you consult the formats described in the documentation, will see that the abbreviated month name should be used %b
, and for the year with 2 digits, it is used %y
.
But there is another detail: when the year has 2 digits, according to the documentation, values between 0 and 68 are mapped for the years 2000 to 2068, and values between 69 and 99 are mapped for the years 1969 and 1999.
It’s not clear what values you want to work with and what dates you want to generate, but if you want change this rule, an alternative would be:
from datetime import datetime
def year_2to4_digit(two_digit_year, pivotyear = 1950):
century = (pivotyear // 100) * 100
if century + two_digit_year > pivotyear:
return century + two_digit_year
return century + 100 + two_digit_year
str_date = 'nov/19'
date = datetime.strptime(str_date, '%b/%y').date()
date = date.replace(year = year_2to4_digit(date.year % 100))
That is, values between 51 and 99 would be converted for the years between 1951 and 1999. The other values (0 to 50) would be between 2000 and 2050. If you want another "cut date", just change the parameter pivotyear
in function year_2to4_digit
. In its specific case ("19"), the API already maps to 2019, which seems to be the desired one. Anyway, I leave the option registered, since years with 2 digits can have this problem and it is important to know how to circumvent it.
Another detail is that for the abbreviated month name, by default is considered to be in English. That is, February will be "Feb", and if you try to do Parsing of the Portuguese version, i.e., "feb", will give error:
str_date = 'fev/19'
date = datetime.strptime(str_date, '%b/%y').date() # ValueError
In your case it is not clear which language is used, since in both English and Portuguese the abbreviation of November is "nov".
But if the idea is to do Parsing of dates in Portuguese, you can use the module locale
:
import locale
# setar locale para português
locale.setlocale(locale.LC_ALL, 'pt_BR.utf8')
str_date = 'fev/19'
date = datetime.strptime(str_date, '%b/%y').date()
Recalling that in this case the locale must be installed in the system, as explained in this reply.
You want November-2019 as output?
– Italo Lemos
You want to convert the nov/19 string to a valid date and continue displaying it as nov/19?
– Daniel Mendes
in fact I ended up discovering my mistake by knowing the other references of strftime because %m is for month in number and %Y is for year in YYYY format, I have already been able to find out which references are appropriate for my case, thanks anyway.
– Viviane Alves Lima
Then put your solution in case someone has the doubt and close the flw question
– Italo Lemos