简体   繁体   English

时间戳的日期时间(第 1 年)引发 ValueError

[英]Datetime to timestamp (year 1) raises ValueError

Goal目标

I want to convert a datetime.datetime object to a timestamp.我想将datetime.datetime object 转换为时间戳。

Code and output代码和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.尝试将datetime.datetime对象的year属性设置为0 ( dt: datetime = datetime(year=0, ...) ) 时也会引发此错误,这是预期的。
Does someone have an explanation for this?有人对此有解释吗? Thanks a lot!非常感谢!

In your code, you use naive datetime (you do not set a timezone), so that object represents local time .在您的代码中,您使用天真的日期时间(您没有设置时区),因此 object 代表本地时间 To calculate Unix time, UTC datetime needs to be determined based on given naive datetime.要计算 Unix 时间,需要根据给定的原始日期时间确定 UTC 日期时间。 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).根据您运行它的机器的时区设置,UTC 日期时间可能位于 0001-01-01 00:00:00 之前(如果您的时区早于 UTC)。 Year 1 is the minimum year , therefore the error.第 1 年是最小年份,因此出现错误。

No issues if you set tz to UTC:如果将 tz 设置为 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

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);通常用于在公历(及其前身儒略历)中对年份进行编号的纪元 (AD) 日历年系统中不存在零年; in this system, the year 1 BC is followed directly by year AD 1.(...)在这个系统中,公元前 1 年直接跟在公元 1 年之后。(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM