2011-11-23 91 views
8

Python的datetime类有一个fromtimestamp方法来创建一个时间戳datetime对象,但不提供其他方式轮一个totimestamp方法...... 我知道,喜欢的东西time.mktime(x.timetuple())你可以转换datetime对象到一个时间戳,但这看起来不是很复杂,所以我很好奇为什么没有totimestamp方法?为什么python datetime类有'fromtimestamp'方法,但不是'totimestamp'方法?

+0

参见http://stackoverflow.com/questions/8022161/python-converting-from-datetime -datetime-to-time-time –

+0

@Sven:我的问题不是要求转换它的方法,而是想知道在'datetime'模块中缺少这种方法的原因... –

+1

我didn不要说这是重复的。我只是链接了相关的信息,这对从Google访问此页面的人来说总是有用。 –

回答

13

我确实记得有关这件事的discussion/bug report,当我回想这段时间的想法。长话短说:提出了很多建议,但由于某种原因,没有人接受。

关键是我觉得最好的this reply总结:

大量提出了一个满意的解决方案。没有人提出一个令你满意的解决方案,因为你已经过度限制了这个问题。在这么多年之后,我们仍然没有utctotimestamp()的原因在于,就我所知,您和您单独拒绝接受一种方法,该方法在工作范围内以微秒精度反转utcfromtimestamp()。这种方法是一个完全合理和可接受的解决方案,并且会为Python作为一种语言增加很多价值。

我怀疑你没有意识到你有多么痛苦无意中造成了Python用户的世界,因为他们单方面阻止了这个问题的进展。我见过他们:学生,朋友,同事 - 即使是非常聪明,有能力的人也会受到阻碍。没有人想到看日历模块。也许如果你看到他们中的一些人与此斗争,你会明白。

最终结果这个故事是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) 
相关问题