Riassumo la discussione in due fasi:
- Converti il formato non elaborato in un
datetimeoggetto.
- Utilizzare la funzione di un
datetimeoggetto o un dateoggetto per calcolare il numero della settimana.
Riscaldamento
`` `Python
from datetime import datetime, date, time
d = date(2005, 7, 14)
t = time(12, 30)
dt = datetime.combine(d, t)
print(dt)
`` `
1 ° passo
Per generare manualmente un datetimeoggetto, possiamo usare datetime.datetime(2017,5,3)o datetime.datetime.now().
Ma in realtà, di solito abbiamo bisogno di analizzare una stringa esistente. possiamo usare la strptimefunzione, ad esempio datetime.strptime('2017-5-3','%Y-%m-%d')in cui devi specificare il formato. I dettagli di codici di formato diverso sono disponibili nella documentazione ufficiale .
In alternativa, un modo più conveniente è usare il modulo dateparse . Esempi sono dateparser.parse('16 Jun 2010'), dateparser.parse('12/2/12')odateparser.parse('2017-5-3')
I due approcci precedenti restituiranno un datetimeoggetto.
2 ° passo
Utilizzare l' datetimeoggetto ottenuto per chiamare strptime(format). Per esempio,
`` `Python
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.
`` `
È molto difficile decidere quale formato utilizzare. Un modo migliore è ottenere un dateoggetto da chiamare isocalendar(). Per esempio,
`` `Python
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
`` `
In realtà, sarà più probabile che utilizzerai date.isocalendar()per preparare un rapporto settimanale, specialmente nella stagione dello shopping "Natale-Capodanno".