GregoirePelegrin
GregoirePelegrin

Reputation: 1185

Datetime to timestamp (year 1) raises ValueError

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!

Upvotes: 1

Views: 94

Answers (2)

FObersteiner
FObersteiner

Reputation: 25594

In your code, you use naive datetime (you do not set a timezone), so that object represents local time. To calculate Unix time, UTC datetime needs to be determined based on given naive datetime. Depending on the timezone setting of the machine you run this on, that UTC datetime could lie before 0001-01-01 00:00:00 (if your timezone is ahead of UTC). 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

Upvotes: 2

Daweo
Daweo

Reputation: 36630

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

Upvotes: -1

Related Questions