开发者

psycopg2 to deal with timestamp without time zone

开发者 https://www.devze.com 2023-01-24 07:11 出处:网络
I obtain a record from PostgreSQL, which its type is timestamp without time zone I am using psycopg2 I might get datetime object if I am using timestamp with time zone. But, currently, this is not t

I obtain a record from PostgreSQL, which its type is timestamp without time zone

I am using psycopg2

I might get datetime object if I am using timestamp with time zone. But, currently, this is not the case. http://initd.org/psycopg/docs/usage.html#time-zones-handling

I realize I am getting float type instead.

How can I suppose to get value like from the given float?

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


The float value that you're getting seems to be milliseconds from the epoch. So this seems to give what you're looking for:

#!/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()
                    )


Update for newer people. As of at least psycopg2 2.7.1, the "timestamp without time zone" returns a datetime.

So your_time.strftime("%a, %d %b %Y %H:%M:%S +0000") now will just work.

0

精彩评论

暂无评论...
验证码 换一张
取 消