stackoverflow 上有一个这样的问题(点击打开链接):
如何将下列样式的字符串转换为datetime object
Jun 1 2005 1:33PM Aug 28 1999 12:00AM(1)上面的答案是这样的:
import time stamp = 'Jun 1 2005 1:33PM' timeobj = time.strptime(stamp, '%b %d %Y %I:%M%p')得到的是一个time.strut_time()对象:
>>>print timeobj struct_time(tm_year=2005, tm_mon=6, tm_mday=1, tm_hour=13, tm_min=33, tm_sec=0, tm_wday=2, tm_yday=152, tm_isdst=-1) >>>type (timeobj) <type 'time.struct_time'>官方文档关于(time.strptime)的解释 点击打开链接
这里需要注意一个地方,小时(Hour)我们一般用%H表示,但是我们使用%p匹'PM',而使用这个的前提是,hour必须是12小时制,所以使用%I
When used with the strptime() function, the %p directive only affects the output hour field if the %I directive is used to parse the hour.
>>> datetimeobj = datetime.strptime(s,'%b %d %Y %I:%M%p') >>> print datetimeobj 2005-06-01 13:33:00 >>> type(datetimeobj) <type 'datetime.datetime'>这样就可以了
官方文档关于(datetime.strptime)的解释点击打开链接