2013-07-31 104 views
3

我知道這在其他地方一定是一個很好的覆蓋問題,但是我在SO上看到的大多數問題看起來像是朝着相反的方向前進。我明白如何從time.time()轉換爲人類可讀的日期時間格式如下:字符串日期時間格式到時間()Python中的unix時間格式

​​

什麼是換去反方向的功能?

>>> 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 

我想從字符串走到時代格式以來的秒數。

UPDATE

這是我使用的是什麼,但似乎不雅---必須是已經做了這個功能,對不對?

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

也許更簡單地說,我只是缺少秒的分數格式代碼?

+0

你在哪個Python版本上? –

+0

看起來像版本2.7.3 – Mittenchops

+0

Py3x有一個更簡單的方法。你仍然失去了一些精度。 –

回答

2

缺少格式爲幾分之一秒。

time.strptime(thetime, "%Y-%m-%d %H:%M:%S.%f")

+0

很酷,我這麼認爲,但似乎仍然下降到小數點後一位。 – Mittenchops

+1

'datetime.strptime(thetime,「%Y-%m-%d%H:%M:%S.%f」)'不 –