可能重复:
Converting unix timestamp string to readable date in Python如何将timestamp字符串转换为datetime对象?
我有一个时间戳:
t = 1322745926.123
如何时间戳转换成datetime对象?
datetime.strptime(t,date_format)
我应该date_format
在上面的函数调用?
可能重复:
Converting unix timestamp string to readable date in Python如何将timestamp字符串转换为datetime对象?
我有一个时间戳:
t = 1322745926.123
如何时间戳转换成datetime对象?
datetime.strptime(t,date_format)
我应该date_format
在上面的函数调用?
datetime.strptime()对于你的问题不是正确的功能。它将像“11月30日00”这样的字符串转换为struct_time对象。
您propably想
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()
datetime.datetime.utcfromtimestamp(1322745926.123)
返回datetime.datetime(2011, 12, 1, 13, 25, 26, 123000)
它在UTC时区。附:
a = pytz.utc.localize(datetime.datetime.utcfromtimestamp(1322745926.123))
你得到一个时区感知DateTime对象可以再转换到你需要的任何时区:
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>)
使用此,
datetime.datetime.fromtimestamp(t)
+1,PyTZ是不错的库,但应该指出,这不是标准的Python安装的一部分。 – mac