2010-11-03 140 views
2

我从WordPress API获取时间戳,但通常的方法converting from timestamp to datetime正在让我失望。在Python中将未知时间戳转换为日期时间

我运行此:

print pages[1]['dateCreated'] 
print datetime.fromtimestamp(pages[1]['dateCreated']) 

而得到这样的:

20100228T09:25:07 
Traceback (most recent call last): 
    File "C:\Python26\Lib\SITE-P~1\PYTHON~1\pywin\framework\scriptutils.py", line 325, in RunScript 
    exec codeObject in __main__.__dict__ 
    File "C:\Documents and Settings\mmorisy\Desktop\My Dropbox\python\betterblogmaster3.py", line 28, in <module> 
    print datetime.fromtimestamp(pages[1]['dateCreated']) 
AttributeError: DateTime instance has no attribute '__float__' 

有什么建议?

+2

['timestamp'应该是一个浮动(http://docs.python.org/library/datetime.html#datetime.date.fromtimestamp)。你有一个字符串,用['datetime.strptime']解析你的字符串(http://docs.python.org/library/datetime.html#datetime.datetime.strptime),你会得到'datetime'对象。 – SilentGhost 2010-11-03 15:14:30

+1

'__main ______ dict__'中的exec codeObject这是干什么用的?如果你想保密你的代码,我们不能帮忙,我们可以吗?此外,如果你真的使用这个,你就错过了使用Python的点。 – 2010-11-03 15:14:57

+1

你有什么是ISO 8601时间戳,而不是Unix时间戳。请参阅http://stackoverflow.com/questions/969285/how-do-i-translate-a-iso-8601-datetime-string-into-a-python-datetime-object – 2010-11-03 15:27:06

回答

3

假设你已经from datetime import datetime

print datetime.strptime(pages[1]['dateCreated'],'%Y%m%dT%H:%M:%S') 
+0

@Michael:与正则表达式无关,日期时间有自己的字符串格式化/解析的模板语言。 – SilentGhost 2010-11-03 15:36:10

+0

感谢你们俩。 – 2010-11-03 19:42:41