我知道这可能是一个被广泛讨论的问题,但是我看到的大多数SO上的问题似乎都是相反的情况。我知道如何将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'
反向行驶的功能是什么?
>>> thetime = '2013-07-30 21:23:14.744643'
>>> time.strptime(thetime, "%Y-%m-%d %H:%M:%S")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/_strptime.py", line 454, in _strptime_time
return _strptime(data_string, format)[0]
File "/usr/lib/python2.7/_strptime.py", line 328, in _strptime
data_string[found.end():])
ValueError: unconverted data remains: .744643
我想把字符串转换成自纪元以来的秒数格式。
更新
这是我正在使用的内容,但它似乎不够优雅——肯定有一个已经完成这个功能的函数,对吗?
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
或许更简单地说,我只是缺少毫秒的格式代码?