MongoDB 的 Python 日期对象
我需要根据用户输入的字符串准备一个日期,以便插入到MongoDB中。
代码:
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())
...
其中,d_created
这个属性工作得很好,但b_birthdate
就不行,因为我用的是Python 2.4,无法使用这里讨论的方法。于是,我只能使用你看到的代码。不过,当我尝试将这个文档插入到MongoDB时,它对d_birthdate
提出了警告。有没有办法将它转换为日期时间对象,或者有没有更好的方法?谢谢。
1 个回答
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')