为什么python datetime类有一个“fromtimestamp”方法,而没有一个“totimestamp”方法?

2024-04-23 10:43:54 发布

您现在位置:Python中文网/ 问答频道 /正文

Python的datetime类有一个fromtimestamp方法,可以根据时间戳创建一个datetime对象,但没有为另一种方式提供totimestamp方法。。。 我知道使用类似time.mktime(x.timetuple())的方法可以将datetime对象转换为时间戳,但这对我来说似乎不必要复杂,所以我很好奇为什么没有{}方法?在


Tags: 对象方法datetimetime方式时间fromtimestampmktime
1条回答
网友
1楼 · 发布于 2024-04-23 10:43:54

我确实记得关于这件事的一个discussion/bug report的事,而我不久前也在想这件事。长话短说:已经提出了很多建议,但由于某些原因,没有一个被接受。在

我认为最好用this reply来概括这一点:

Plenty have proposed a satisfactory solution. No one has come up with a solution that is satisfactory to you, because you have overconstrained the problem. The reason we still have no utctotimestamp() after all these years is that you, and you alone as far as I know, refuse to accept a method that inverts utcfromtimestamp() with microsecond precision over its working range. Such a method is a perfectly reasonable and acceptable solution and would add a lot of value to Python as a language.

I suspect you don't realize just how much pain you have unintentionally caused the world of Python users by singlehandedly blocking progress on this issue. I've seen them: students, friends, coworkers even very smart and capable people are stymied by it. No one thinks of looking in the calendar module. Maybe if you watched some of them struggle with this, you would understand.

这个故事的最终结果是documentation was added关于如何自己动手:

# On the POSIX compliant platforms, `utcfromtimestamp(timestamp)` is
# equivalent to the following expression:
datetime(1970, 1, 1) + timedelta(seconds=timestamp)

# There is no method to obtain the timestamp from a `datetime` instance,
# but POSIX timestamp corresponding to a `datetime` instance `dt` can be
# easily calculated as follows. For a naive `dt`:
timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)

# And for an aware ``dt``::
timestamp = (dt - datetime(1970, 1, 1, tzinfo=timezone.utc)) / timedelta(seconds=1)

相关问题 更多 >