2011-02-18 117 views
1
from time import time 
time() # Gives me 1298046251.375916 

我需要01/01/2011 01:48:36.157轉換爲同樣的時間戳和我比較熟悉Python的日期/時間庫。什麼是最簡單的方法來完成這一點?是否有相當於strtotime的功能?在Python轉換時間戳UNIX時間戳

考慮到MongoDB wants a datetime object它也會被接受而不是unix風格的時間戳。

回答

3

短anwser:

>>> datetime.datetime.strptime ? 
Type:  builtin_function_or_method 
Base Class: <type 'builtin_function_or_method'> 
String Form: <built-in method strptime of type object at 0xb70b3520> 
Namespace: Interactive 
Docstring: 
    string, format -> new datetime parsed from a string (like time.strptime()). 

Documentation reference

全解析看起來像:

>>> d = datetime.strptime("01/01/2011 01:48:36.157", "%m/%d/%Y %H:%M:%S.%f") 

你可以將其轉換爲一個時間戳:

import time 
time.mktime(d.timetuple()) 
+0

I *只是*發現坐在`datetime`頁及成品的底部制定出公式。謝謝! – 2011-02-18 16:32:08