ValueError: year is out of range in Python

avatar

Borislav Hadzhiev

Last updated: Apr 24, 2022

banner

Photo from Unsplash

ValueError: year is out of range in Python #

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).

valueerror year is out of range

Here is an example of how the error occurs.

main.py
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.

main.py
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.

main.py
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.

main.py
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 run where we set the d variable to the current local datetime.

Conclusion #

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).

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.