2010-11-11 168 views
2

我获得PostgreSQL的记录,这类型为timestamp without time zonepsycopg2处理时间戳没有时区

我使用的psycopg2

如果我使用timestamp with time zone我可能会datetime对象。但是,目前情况并非如此。 http://initd.org/psycopg/docs/usage.html#time-zones-handling

我意识到我正在获得浮动类型。

我该如何从给定的浮点数获​​得值?

Jan 07, 2010 
16:38:49 

connection.cursor.execute(sql, data) 
    records = connection.cursor.fetchall() 

    # In PostgreSQL, type is "timestamp without time zone" 

    # <type 'float'> 
    print type(record['_start_timestamp']) 
    # 1.28946608161e+12 
    print record['_start_timestamp'] 
    # TypeError: argument must be 9-item sequence, not float 
    print time.strftime("%a, %d %b %Y %H:%M:%S +0000", record['_start_timestamp']) 

回答

3

你得到的float值似乎是从毫秒为单位。所以这似乎给你要找的东西:

#!/usr/bin/python 

from datetime import datetime 
import time 

your_time = 1.28946608161e+12 

print time.strftime("%a, %d %b %Y %H:%M:%S +0000", 
        datetime.fromtimestamp(your_time/1000).timetuple() 
        ) 
+0

太棒了!谢谢! – 2010-11-12 01:44:20

0

更新的人。至少psycopg2 2.7.1,“没有时区的时间戳”返回一个日期时间。

所以your_time.strftime("%a, %d %b %Y %H:%M:%S +0000")现在只会工作。