python 时间的格式转化,格式为20130415172500字符串转为datetime类型

2024-11-30 17:05:44
推荐回答(2个)
回答1:

python编程用datetime方法进行时间转换,代码如下:

$ python
Python 2.7.2+ (default, Jul 20 2012, 22:12:53) 
[gcc 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> dtstr = "20130415172559"
>>> dt = datetime.datetime.strptime(dtstr, "%Y%m%d%H%M%S")
>>> dt
datetime.datetime(2013, 4, 15, 17, 25, 59)
>>> another_dt = dt+datetime.timedelta(seconds=2)
>>> another_dt
datetime.datetime(2013, 4, 15, 17, 26, 1)
>>>

回答2:

$ python
Python 2.7.2+ (default, Jul 20 2012, 22:12:53)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> dtstr = "20130415172559"
>>> dt = datetime.datetime.strptime(dtstr, "%Y%m%d%H%M%S")
>>> dt
datetime.datetime(2013, 4, 15, 17, 25, 59)
>>> another_dt = dt+datetime.timedelta(seconds=2)
>>> another_dt
datetime.datetime(2013, 4, 15, 17, 26, 1)
>>>