2

I'm getting a timestamp back from the WordPress API, but the usual method of converting from timestamp to datetime is failing me.

I run this:

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

And get this:

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__'

Any suggestions?

Community
  • 1
  • 1
Michael Morisy
  • 2,495
  • 2
  • 23
  • 26
  • 2
    [`timestamp` supposed to be a float](http://docs.python.org/library/datetime.html#datetime.date.fromtimestamp). You have a string, parse your string with [`datetime.strptime`](http://docs.python.org/library/datetime.html#datetime.datetime.strptime) and you'll get `datetime` object. – SilentGhost Nov 03 '10 at 15:14
  • 1
    `exec codeObject in __main__.__dict__` What does this do? If you're going to keep your code secret, we can't help much, can we? Further, if you're actually using this, you're missing the point of using Python. – S.Lott Nov 03 '10 at 15:14
  • 1
    What you've got there is an ISO 8601 timestamp, not a Unix timestamp. See http://stackoverflow.com/questions/969285/how-do-i-translate-a-iso-8601-datetime-string-into-a-python-datetime-object – Robie Basak Nov 03 '10 at 15:27
  • @SilentGhost thanks, that was very helpful. @S.Lott, I was trying to keep out the noise. _main_._dict_ was from a library, not something I'm trying to hide, but I don't see how I'm "missing the point of using Python"? I'll try and include more relevant information next time. – Michael Morisy Nov 03 '10 at 15:34
  • `exec` misses the point of using Python. It's already a dynamic language. Using exec makes a dynamic language dynamic. Largely a waste of time. Code is not "noise". – S.Lott Nov 03 '10 at 18:22
  • @S.Lott I see what you're saying. I think that's from WinPython's handling of Python. – Michael Morisy Nov 03 '10 at 19:42

1 Answers1

3

Assume you've from datetime import datetime:

print datetime.strptime(pages[1]['dateCreated'],'%Y%m%dT%H:%M:%S')
MattH
  • 37,273
  • 11
  • 82
  • 84
  • @Michael: that has nothing to do with regex, the datetime has their own templating language for string formatting/parsing. – SilentGhost Nov 03 '10 at 15:36