2

I'm needing to prepare a date for insertion into MongoDB based on user input (string).

Code:

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())
...

The d_created attribute works fine, but b_birthdate doesn't since I'm on Python 2.4, and I can't use the method discussed here. So, I had to use the code you see above. However, when I try to insert this document into MongoDB, it complains about d_birthdate. Is there a way to convert it to a datetime object or maybe some better method? Thanks.

Community
  • 1
  • 1
Donnie
  • 6,229
  • 8
  • 35
  • 53

1 Answers1

3

You can convert the time.time_struct object to a datetime.datetime object:

from datetime import datetime
from time import mktime

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

In newer versions of Python (I'm fairly sure you can't in 2.4) you could do:

self.d_birthdate = datetime.strptime('6/8/1980', '%m/%d/%Y')
Zach Kelling
  • 52,505
  • 13
  • 109
  • 108
  • 1
    You are right about not being able to use `datetime.strptime` in 2.4. This is exactly what I needed. =) – Donnie Jun 09 '11 at 13:19