我有类似的东西
s= "2010-02-12 12:12:10"
r= repr(datetime.datetime(*time.strptime(s, "%Y-%m-%d %H:%M:%S")[:6]))
print r
打印出的值为datetime.datetime(2010, 2, 12, 12, 12, 10)
我的问题是:如何访问r中的每个值?例如,我只想要年份的价值,即2012年。我尝试做r [0],但它给了我字母'd'而不是......
谢谢!
答案 0 :(得分:6)
为什么使用repr()
?
>>> s = "2010-02-12 12:12:10"
>>> r = datetime.datetime(*time.strptime(s, "%Y-%m-%d %H:%M:%S")[:6])
>>> r.year
2010
此处有关date
个对象的更多信息:http://docs.python.org/library/datetime.html#date-objects
答案 1 :(得分:6)
使用repr
将其转换为字符串(或实际上是Python可以使用的datetime
对象的*表示.str()用于将事物转换为字符串。)
保持简单:
>>> r = datetime.datetime(*time.strptime(s, "%Y-%m-%d %H:%M:%S")[:6])
>>> r.year
2010
答案 2 :(得分:2)
您可以直接访问年份属性
datetime.date.today().year