Borislav Hadzhiev
Sun Apr 24 2022·2 min read
Photo by Hayden Dib
The Python "ValueError: year is out of range" occurs when we pass a timestamp
that is out of range to the fromtimestamp()
method. To solve the error, divide
the timestamp by 1000
if it is in milliseconds, e.g.
datetime.fromtimestamp(my_ms / 1000)
.
Here is an example of how the error occurs.
from datetime import datetime timestamp_in_ms = 1654618085225 # ⛔️ ValueError: year 54402 is out of range d = datetime.fromtimestamp(timestamp_in_ms)
The datetime.fromtimestamp()
method takes a timestamp in seconds, but we
passed it a timestamp in milliseconds which caused the error.
You can convert the milliseconds to seconds by dividing by 1000
.
from datetime import datetime timestamp_in_ms = 1654618085225 d = datetime.fromtimestamp(timestamp_in_ms / 1000) print(d) # 👉️ "2022-06-07 19:08:05.225000"
If you want to preserve the millisecond precision, use float division by
dividing by 1000.0
instead.
from datetime import datetime timestamp_in_ms = 1654618085225 d = datetime.fromtimestamp(timestamp_in_ms / 1000.0) print(d) # 👉️ "2022-06-07 19:08:05.225000"
The datetime.fromtimestamp method takes a timestamp in milliseconds and returns the corresponding local date and time.
If the optional tz
argument is not provided, the timestamp is converted to the
platform's local date and time.
The method raises ValueError
if the timestamp is out of supported values.
You can also use a try/except
block to handle the error in a way that suits
your use case.
from datetime import datetime timestamp_in_ms = 1654618085225 try: d = datetime.fromtimestamp(timestamp_in_ms) except ValueError: # 👇️ this runs print('except block runs') d = datetime.today() print(d) # 👉️ "2022-06-07 19:29:06.375292"
We pass the timestamp to the fromtimestamp()
method and if a ValueError
is
raised, the except block is ran where we set the d
variable to the current
local datetime.