5

Possible Duplicate:
Converting unix timestamp string to readable date in Python

I have a timestamp:

t = 1322745926.123

How to convert timestamp to datetime object ?

datetime.strptime(t,date_format)

What should date_format be in the above function call?

Community
  • 1
  • 1
Bdfy
  • 23,141
  • 55
  • 131
  • 179

3 Answers3

10

datetime.strptime() is not the right function for your problem. It convertes a string like "30 Nov 00" to a struct_time object.

You propably want

from datetime import datetime
t = 1322745926.123
datetime.fromtimestamp(t).isoformat()

The result from this code is

'2011-12-01T14:25:26.123000'

if your timecode is a string you can do this:

from datetime import datetime
t = "1322745926.123"
datetime.fromtimestamp(float(t)).isoformat()
Pascal Rosin
  • 1,498
  • 16
  • 27
3
datetime.datetime.utcfromtimestamp(1322745926.123)

returns datetime.datetime(2011, 12, 1, 13, 25, 26, 123000) which is in the UTC timezone. With:

a = pytz.utc.localize(datetime.datetime.utcfromtimestamp(1322745926.123))

you get a timezone-aware datetime object which can be then converted to any timezone you need:

a == datetime.datetime(2011, 12, 1, 13, 25, 26, 123000, tzinfo=<UTC>)

a.astimezone(pytz.timezone('Europe/Paris'))

# datetime.datetime(2011, 12, 1, 14, 25, 26, 123000, tzinfo=<DstTzInfo 'Europe/Paris' CET+1:00:00 STD>)
eumiro
  • 207,213
  • 34
  • 299
  • 261
  • +1, PyTZ is a nice library, but it should be noted that is not part of the standard python installation. – mac Dec 06 '11 at 13:39
2

Use this,

datetime.datetime.fromtimestamp(t)
Jim Jose
  • 1,319
  • 11
  • 17