如果我假设字符串为"2008-12-12 19:21:10“,我如何将其转换为日期,并从创建对象中分别获取年、月和日?
发布于 2012-09-15 02:50:49
使用datetime.datetime.strptime()
function
from datetime import datetime
dt = datetime.strptime(datestring, '%Y-%m-%d %H:%M:%S')
现在您有了一个datetime.datetime
对象,它具有.year
、.month
和.day
属性:
>>> from datetime import datetime
>>> datestring = "2008-12-12 19:21:10"
>>> dt = datetime.strptime(datestring, '%Y-%m-%d %H:%M:%S')
>>> print dt.year, dt.month, dt.day
2008 12 12
发布于 2017-06-27 02:36:06
strptime在这里你可以找到https://www.tutorialspoint.com/python/time_strptime.htm ()方法的完整描述。在那里你可以找到所有类型的字符串。例如:-将字符串转换为'15-MAY-12‘
>>>from datetime import datetime
>>>datestring = "15-MAY-12"
>>>dt = datetime.strptime(datestring, '%d-%b-%Y')
>>>print(dt.year, dt.month, dt.day)
2012 MAY 15
发布于 2018-06-21 05:51:06
有一件事需要补充;请注意,%y
是两位数的年份符号,%Y
是四位数的年份符号:
import datetime
datestring = '15-MAY-12'
print(datetime.datetime.strptime(datestring, '%d-%b-%y'))
>>> datetime.datetime(2012, 5, 15, 0, 0)
datestring = '15-MAY-2012'
print(datetime.datetime.strptime(datestring, '%d-%b-%Y'))
>>> datetime.datetime(2012, 5, 15, 0, 0)
https://stackoverflow.com/questions/12430287
复制相似问题