2015-12-16 11 views
6

so come ottenere la data:Puoi fare somme con un datetime in Python?

from datetime import datetime 
time = datetime.now() 
print(time) 

Ma c'è un modo in cui è possibile definire i giorni/ore fino a una certa data, forse memorizzare la data come un numero intero o qualcosa del genere? Thx per tutte le risposte

risposta

0

Ho preso la tua risposta e sviluppato in modo che l'utente può inserire la data che vogliono : Qui è

from datetime import datetime 
year=int(input("What year?")) 
month=int(input("What month?")) 
day=int(input("What day?")) 
hour=int(input("What hour?")) 
minute=int(input("What minute?")) 
second=int(input("What second?")) 
then = datetime(year,month,day,hour,minute,second) 
now = datetime.now() 
diff = then - now 
print(diff) 

print(diff.total_seconds()) 

Th voi tutti anks per le vostre risposte: D

Ora Variabile

Qui è ancora meglio di codice, si può semplicemente prendere l'ormai variabile e metterlo direttamente nel integer differenza


from datetime import datetime 
while True: 
    inp = input("Enter date in format yyyy/mm/dd hh:mm:ss") 
    try: 
     then = datetime.strptime(inp, "%Y/%m/%d %H:%M:%S") 
     break 
    except ValueError: 
     print("Invalid input") 
diff = then - datetime.now() 
print(diff, "until", inp) 
print(diff.total_seconds(),"seconds") 
+0

Puoi farlo con una singola stringa, lo aggiungerò alla mia risposta –

+0

Modificato tu modifichi [;). ] In modo che appare come segue: –

+0

da datetime import datetime while True: inp = input ("Immettere la data nel formato AAAA/MM/gg hh: mm: ss") prova: poi = datetime.strptime (inp, "% Y /% m /% d% H:% m:% S") pausa except ValueError: stampa ("input non valido") ora = datetime.now() diff = allora - ora stampa (diff, "until", inp) stampa (diff.total_seconds(), "secondi") –

7

Basta creare un altro oggetto datetime e sottrarre che fornirà un oggetto timedelta.

from datetime import datetime 
now = datetime.now() 
then = datetime(2016,1,1,0,0,0) 
diff = then - now 
print(diff) 

print(diff.total_seconds()) 

15 days, 3:42:21.408581 
1309365.968044 

Se si vuole prendere l'input dell'utente:

from datetime import datetime 


while True: 
    inp = input("Enter date in format yyyy/mm/dd hh:mm:ss") 
    try: 
     then = datetime.strptime(inp, "%Y/%m/%d %H:%M:%S") 
     break 
    except ValueError: 
     print("Invalid input") 

now = datetime.now() 
diff = then - now 
print(diff) 

Demo:

$Enter date in format yyyy/mm/dd hh:mm:ss2016/01/01 00:00:00 
15 days, 3:04:51.960110 
+0

Thx, pensato che potrebbe essere qualcosa di semplice come quello –

+0

Err, hai dimenticato i collegamenti al documento. : D –

+0

@BhargavRao, stavo solo testando per vedere se eri online;) –

Problemi correlati