代码之家  ›  专栏  ›  技术社区  ›  Cheok Yan Cheng

psycopg2处理不带时区的时间戳

  •  2
  • Cheok Yan Cheng  · 技术社区  · 15 年前

    我从PostgreSQL获得一条记录,它的类型是 timestamp without time zone

    我在用psycopg2

    datetime 对象如果我使用 timestamp with time zone 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'])
    
    2 回复  |  直到 8 年前
        1
  •  3
  •   mjhm    15 年前

    你得到的浮点值似乎是从纪元开始的毫秒。所以这似乎给了你想要的:

    #!/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()
                        )
    
        2
  •  0
  •   blb    8 年前

    所以 your_time.strftime("%a, %d %b %Y %H:%M:%S +0000") 现在就行了。