4

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
  • 21,109
  • 53
  • 126
  • 178

3 Answers3

8

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,458
  • 16
  • 26
2
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
  • 194,053
  • 32
  • 286
  • 259
  • +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,279
  • 10
  • 17