2011-06-09 109 views
2

我需要根據用戶輸入(字符串)準備插入MongoDB的日期。MongoDB的Python日期對象

代碼:

from datetime import datetime 
import time 
... 
self.d_birthdate = time.strptime('6/8/1980', '%m/%d/%Y') 
self.d_created = dict.get('d_created', datetime.now()) 
... 

的​​屬性工作正常,但由於我對Python的2.4 b_birthdate不,我不能使用的方法討論here。所以,我必須使用你在上面看到的代碼。但是,當我嘗試將此文檔插入MongoDB時,它抱怨d_birthdate。有沒有辦法將它轉換爲日期時間對象或者更好的方法?謝謝。

回答

3

您可以將time.time_struct對象轉換爲datetime.datetime對象:

from datetime import datetime 
from time import mktime 

birthdate = time.strptime('6/8/1980', '%m/%d/%Y') 
self.d_birthdate = datetime.fromtimestamp(mktime(birthdate)) 

在Python的新版本(我相當肯定你不能在2.4),你可以這樣做:

self.d_birthdate = datetime.strptime('6/8/1980', '%m/%d/%Y') 
+1

你在2.4中不能使用'datetime.strptime'是對的。這正是我需要的。 =) – Donnie 2011-06-09 13:19:14