Resumo la discusión en dos pasos:
- Convierta el formato sin formato en un
datetimeobjeto.
- Use la función de un
datetimeobjeto o un dateobjeto para calcular el número de semana.
Calentar
`` `pitón
from datetime import datetime, date, time
d = date(2005, 7, 14)
t = time(12, 30)
dt = datetime.combine(d, t)
print(dt)
`` `
1er paso
Para generar un datetimeobjeto manualmente , podemos usar datetime.datetime(2017,5,3)odatetime.datetime.now() .
Pero en realidad, generalmente necesitamos analizar una cadena existente. podemos usar la strptimefunción, como datetime.strptime('2017-5-3','%Y-%m-%d')en la que debe especificar el formato. Se pueden encontrar detalles de diferentes formatos en la documentación oficial .
Alternativamente, una forma más conveniente es usar el módulo dateparse . Ejemplos son dateparser.parse('16 Jun 2010'), dateparser.parse('12/2/12')odateparser.parse('2017-5-3')
Los dos enfoques anteriores devolverán un datetimeobjeto.
2do paso
Usa el datetimeobjeto obtenido para llamar strptime(format). Por ejemplo,
`` `pitón
dt = datetime.strptime('2017-01-1','%Y-%m-%d') # return a datetime object. This day is Sunday
print(dt.strftime("%W")) # '00' Monday as the 1st day of the week. All days in a new year preceding the 1st Monday are considered to be in week 0.
print(dt.strftime("%U")) # '01' Sunday as the 1st day of the week. All days in a new year preceding the 1st Sunday are considered to be in week 0.
print(dt.strftime("%V")) # '52' Monday as the 1st day of the week. Week 01 is the week containing Jan 4.
`` `
Es muy difícil decidir qué formato usar. Una mejor manera es obtener un dateobjeto para llamar isocalendar(). Por ejemplo,
`` `pitón
dt = datetime.strptime('2017-01-1','%Y-%m-%d') # return a datetime object
d = dt.date() # convert to a date object. equivalent to d = date(2017,1,1), but date.strptime() don't have the parse function
year, week, weekday = d.isocalendar()
print(year, week, weekday) # (2016,52,7) in the ISO standard
`` `
En realidad, será más probable que lo use date.isocalendar()para preparar un informe semanal, especialmente en la temporada de compras "Navidad-Año Nuevo".