如何将timestamp字符串转换为datetime对象?

时间:2011-12-06 13:30:51

标签: python time

  

可能重复:
  Converting unix timestamp string to readable date in Python

我有时间戳:

t = 1322745926.123

如何将时间戳转换为datetime对象?

datetime.strptime(t,date_format)

上述函数调用中date_format应该是什么?

3 个答案:

答案 0 :(得分:4)

datetime.strptime()不适合您的问题。它将类似“30 Nov 00”的字符串转换为struct_time对象。

你可能想要

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

此代码的结果是

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

如果你的时间码是一个字符串,你可以这样做:

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

答案 1 :(得分:2)

datetime.datetime.utcfromtimestamp(1322745926.123)

返回UTC时区中的datetime.datetime(2011, 12, 1, 13, 25, 26, 123000)。用:

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

你会得到一个时区感知的日期时间对象,然后可以将其转换为你需要的任何时区:

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>)

答案 2 :(得分:2)

使用此,

datetime.datetime.fromtimestamp(t)