timestamp() și fromtimestamp() în Python

Dată și oră Python 3.3+ (timestamp); utcnow/utcfromtimestamp învechite din 3.12

Conversia între date și timestamp-uri Unix (secunde de la 1 ianuarie 1970 UTC).

Sintaxă
dt.timestamp()
datetime.fromtimestamp(ts, tz=None)
date.fromtimestamp(ts)

Ce face timestamp() și fromtimestamp()

Un timestamp Unix este numărul de secunde trecute de la 1 ianuarie 1970, ora 00:00 UTC. dt.timestamp() transformă un datetime în timestamp, iar datetime.fromtimestamp(ts, tz) face invers. date.fromtimestamp(ts) dă doar data locală.

Fără fus orar, ambele direcții folosesc ora locală a calculatorului, deci rezultatul diferă de la un server la altul. Dă mereu tz=timezone.utc (sau alt fus). datetime.utcnow() și datetime.utcfromtimestamp() sunt învechite din Python 3.12, pentru că returnează date naive care par locale; folosește datetime.now(timezone.utc) și datetime.fromtimestamp(ts, timezone.utc).

Parametri

Parametru Descriere
ts Timestamp-ul, în secunde (poate avea zecimale).
tz Fusul orar al rezultatului.

Ce returnează

timestamp: float. fromtimestamp: datetime sau date.

Exemple

Exemplul 1: Conversii cu fus orar explicit

from datetime import datetime, date, timezone
d = datetime(2026, 10, 19, 12, 0, tzinfo=timezone.utc)
ts = d.timestamp()
print(ts)
print(datetime.fromtimestamp(ts, tz=timezone.utc))
print(datetime.fromtimestamp(0, timezone.utc))
print(date.fromtimestamp(ts))

Rezultat

1792411200.0
2026-10-19 12:00:00+00:00
1970-01-01 00:00:00+00:00
2026-10-19

Exemplul 2: Funcțiile învechite utcnow și utcfromtimestamp

import datetime
print(datetime.datetime.utcnow())
print(datetime.datetime.utcfromtimestamp(0))

Rezultat (cu avertismentele afișate de Python 3.12+)

exemplu.py:2: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).
2026-10-19 11:32:07.418205
exemplu.py:3: DeprecationWarning: datetime.datetime.utcfromtimestamp() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.fromtimestamp(timestamp, datetime.UTC).
1970-01-01 00:00:00

Greșeli frecvente

  • Apelezi timestamp() pe un datetime naiv pe un server setat pe UTC și pe laptopul tău setat pe ora României: obții valori diferite cu 2-3 ore.
  • Primești un timestamp în milisecunde (de la JavaScript) și îl dai direct lui fromtimestamp: împarte întâi la 1000.

Comenzi înrudite