Monday, February 22, 2010

strptime

Can't find strptime in datetime because you're working in a Python 2.4 environment?


Python 2.4.3 (#1, Jul 27 2009, 17:56:30)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> d = datetime.strptime("21-JAN-08", "%d-%b-%y")
Traceback (most recent call last):
File "", line 1, in ?
AttributeError: type object 'datetime.datetime' has no attribute 'strptime'


strptime was added to datetime in 2.5. Prior to 2.5 you pull it from the typically lower-level library 'time'.


>>> import time
>>> time.strptime("21-JAN-08", "%d-%b-%y")
(2008, 1, 21, 0, 0, 0, 0, 21, -1)


Ah, there it is. Of course, you wanted a datetime, didn't you?


>>> t = time.strptime("21-JAN-08", "%d-%b-%y")
>>> datetime(*t[0:6])
>>> datetime.datetime(2008, 1, 21, 0, 0)

1 comment:

剩沒底天 said...

幽默並不是諷刺,它或許帶有溫和的嘲諷,卻不傷人,它可能是以別人,也可以用自己為對象。..................................................