Home > Back-end >  Datetime to timestamp (year 1) raises ValueError
Datetime to timestamp (year 1) raises ValueError

Time:01-06

Goal

I want to convert a datetime.datetime object to a timestamp.

Code and output

from datetime import datetime

dt1: datetime = datetime(year=2023, month=1, day=6)
ts1: int = dt1.timestamp()
# > 1672959600.0
dt2: datetime = datetime(year=1, month=1, day=2)
ts2: int = dt2.timestamp()
# > -62135510961.0
dt3: datetime = datetime(year=1, month=1, day=1)
ts3: int = dt3.timestamp()
# > Traceback (most recent call last):
# >   File "<stdin>", line 1, in <module>
# > ValueError: year 0 is out of range

Issue

I don't understand why this error is raised. This error also is raised when trying to set a datetime.datetime object's year attribute to 0 (dt: datetime = datetime(year=0, ...)), which is here expected.
Does someone have an explanation for this? Thanks a lot!

CodePudding user response:

In your code, you use naive datetime (you do not set a timezone), so that object represents local time. For Unix time to be calculated, UTC datetime needs to be determined from the naive datetime. Depending on the timezone setting on the machine you run this on, that UTC datetime could lie before year 1. Year 1 is the minimum year, therefore the error.

No issues if you set tz to UTC:

from datetime import datetime, timezone

dt3: datetime = datetime(year=1, month=1, day=1, tzinfo=timezone.utc)
ts3: int = dt3.timestamp()
print(ts3)
# -62135596800.0

CodePudding user response:

Does someone have an explanation for this?

There was not year zero in European calendars

A year zero does not exist in the Anno Domini (AD) calendar year system commonly used to number years in the Gregorian calendar (nor in its predecessor, the Julian calendar); in this system, the year 1 BC is followed directly by year AD 1.(...)

  • Related