Un timestamp è una sequenza di caratteri o informazioni codificate utilizzata per scoprire quando si è verificato un particolare evento, generalmente fornendo la data e l'ora del giorno, con una precisione di una piccola frazione di secondo. In questo articolo impareremo come farlo Ottieni il timestamp corrente in Python . Esistono diversi modi per ottenere il timestamp corrente in Python, possiamo usare le funzioni dai moduli ora, dataora E calendario . 1. Utilizzo del tempo del modulo: IL tempo Il modulo fornisce varie funzioni legate al tempo. La funzione time restituisce il tempo in secondi trascorso dall'epoca come numero in virgola mobile. L'epoca è definita come il punto in cui inizia il tempo e dipende dalla piattaforma.
Syntax: time.time() Parameters: NA Return: floating point number expressed in seconds.>
python3
# using time module> import> time> # ts stores the time in seconds> ts>=> time.time()> # print the current timestamp> print>(ts)> |
>
>
numpy linspace
Produzione:
1594819641.9622827>
2. Utilizzo del modulo datetime: IL appuntamento il modulo fornisce classi per manipolare date e orari. Sebbene sia supportata l'aritmetica di data e ora, l'obiettivo dell'implementazione è l'estrazione efficiente degli attributi per la formattazione e la manipolazione dell'output. La funzione datetime.datetime.now che restituisce il numero di secondi trascorsi dall'epoca.
Syntax: datetime.now() Parameters: tz (time zone) which is optional. Return: the current local date and time.>
python3
# using datetime module> import> datetime;> # ct stores current time> ct>=> datetime.datetime.now()> print>('current time:>->', ct)> # ts store timestamp of current time> ts>=> ct.timestamp()> print>('timestamp:>->', ts)> |
>
>
Produzione:
current time:- 2020-07-15 14:30:26.159446 timestamp:- 1594823426.159446>
3. Utilizzo del calendario del modulo: Possiamo anche ottenere il timestamp combinando più funzioni da più moduli. In questo useremo la funzione calendar.timegm per convertire la tupla che rappresenta l'ora corrente.
Syntax: calendar.timegm(tuple) Parameters: takes a time tuple such as returned by the gmtime() function in the time module. Return: the corresponding Unix timestamp value.>
python3
# using calendar module> # using time module> import> calendar;> import> time;> # gmt stores current gmtime> gmt>=> time.gmtime()> print>('gmt:>->', gmt)> # ts stores timestamp> ts>=> calendar.timegm(gmt)> print>('timestamp:>->', ts)> |
>
>
Produzione:
gmt:- time.struct_time(tm_year=2020, tm_mon=7, tm_mday=15, tm_hour=19, tm_min=21, tm_sec=6, tm_wday=2, tm_yday=197, tm_isdst=0) timestamp:- 1594840866