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