Last updated: Apr 8, 2024
Reading timeยท2 min
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.
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"
A timestamp that is in milliseconds will have a length of 13.
timestamp_in_ms = 1654618085225 print(len(str(timestamp_in_ms))) # ๐๏ธ 13 timestamp_in_seconds = timestamp_in_ms / 1000 print(timestamp_in_seconds) # ๐๏ธ 1654618085.225
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) # ๐๏ธ "2023-07-21 16:29:11.504679"
We pass the timestamp to the fromtimestamp()
method and if a ValueError
is
raised, the except block is run where we set the d
variable to the current
local date and time.
An alternative way to solve the error is to check for the length of the
timestamp before calling the fromtimestamp()
method.
from datetime import datetime timestamp = 1654618085225 if len(str(timestamp)) == 13: d = datetime.fromtimestamp(timestamp / 1000) # ๐๏ธ this runs print('The TS was in ms', d) # ๐๏ธ "2022-06-07 19:08:05.225000" else: d = datetime.fromtimestamp(timestamp) print('The TS was in seconds', d)
If the timestamp has a length of 13
, it is most likely in milliseconds, so we
divide it by 1000
to convert it to seconds before calling fromtimestamp()
.
Otherwise, we call the fromtimestamp()
method directly with the timestamp.
You can learn more about the related topics by checking out the following tutorials: