字符串datetime format to time()python中的unix时间格式

2024-10-01 13:37:49 发布

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

我知道这在其他地方肯定是个很好的问题,但我看到的大多数问题看起来都是反方向的。我了解如何将time.time()转换为人类可读的日期时间格式,如下所示:

>>> import time, datetime
>>> thetime = time.time()
>>> thetime
1375289544.41976
>>> datetime.datetime.fromtimestamp(thetime).strftime("%Y-%m-%d %H:%M:%S")
'2013-07-31 12:51:08'

反方向的作用是什么?在

^{pr2}$

我想从字符串到epoch格式后的秒数。在

更新

这就是我正在使用的,但它看起来不雅观——一定有一个函数已经做到了,对吧?在

def datetostamp(x):
    thetime = x.split('.')
    return(time.mktime(time.strptime(thetime[0], "%Y-%m-%d %H:%M:%S")) + float('.'+thetime[1]))

>>> thetime = '2013-07-30 21:23:14.744643'
>>> datetostamp(thetime)
1375233794.744643

更新2

也许更简单,我只是少了几秒钟的格式代码?在


Tags: 字符串importdatetimetime格式地方时间人类