I have a list of dates, in string format, ranging from "01/01/2000" to "31/12/2022". If I assume the academic year runs from 1st September to 31st August, how can I return the academic year, in the format "2018-19"?
Presently I'm going down the route of converting the string to an integer :-
import datetime
def give_academic_year(theDate):
utc_time = datetime.datetime.strptime(theDate, '%d/%m/%Y')
a = datetime.datetime.timestamp(utc_time)
# Now I was going to do some cluncky comparison for each academic year
if a>946684800 and a<978307200:
return "2000-01"
elif a>978307200 and a<1009756800:
return "2001-02"
etc.
But there is probably a much more elegant way of doing this?
CodePudding user response:
you could do it in the following way just playing with the year and the formats from the datetime function of the same library.
from datetime import datetime
def give_academic_year(theDate):
if theDate.month > 8:
return '{0}-{1}'.format(theDate.year, int(theDate.strftime('%y')) 1)
else:
return '{0}-{1}'.format((theDate.year-1), theDate.strftime('%y'))
# example
theDate = datetime.strptime('01/03/2020', '%d/%m/%Y')
give_academic_year(theDate)
then it only remains to apply the function to the list, you can do it with a lambda expression.
regards.
CodePudding user response:
Oh, @slothrop, that is elegant! I didn't know about those attributes.
So this seems to do the job for me :-
if utc_time.month>8:
acam_year=str(utc_time.year) "-" str((utc_time.year 1)-2000)
else:
acam_year=str(utc_time.year-1) "-" str((utc_time.year)-2000)
return acam
Just the ticket - thanks very much.