您的位置:首页 > 移动开发 > Objective-C

'Jun 1 2005 1:33PM' 转换为datetime object

2014-10-06 09:39 555 查看
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.


(2)可是不是要求转化为datetime object吗?目前的格式是time.strut_time,这样保存进数据库是不行的.

>>> 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)的解释点击打开链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐