问题描述:

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?

网友答案:

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()
网友答案:

Use this,

datetime.datetime.fromtimestamp(t)
网友答案:
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>)
相关阅读:
Top