如何将字符串转换为日期对象并分别获取年,月和日? [英] How can I convert a string into a date object and get year, month and day separately?
本文介绍了如何将字符串转换为日期对象并分别获取年,月和日?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我可以说这个字符串 2008-12-12 19:21:10,如何将其转换为日期,并分别从创建的对象中获取年,月和日?
If I have lets say this string "2008-12-12 19:21:10" how can I convert it into a date and get the year, month and day from that created object separately?
推荐答案
使用 datetime.datetime.strptime()
函数:
from datetime import datetime
dt = datetime.strptime(datestring, '%Y-%m-%d %H:%M:%S')
现在您有一个 datetime.datetime
对象,它具有 .year
, .month
和 .day
属性:
Now you have a datetime.datetime
object, and it has .year
, .month
and .day
attributes:
>>> 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
这篇关于如何将字符串转换为日期对象并分别获取年,月和日?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文