2011-02-18 144 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