2017-03-17 43 views
0

我有以下幾點:python腳本轉換保存日期以UTC

import psycopg2 
from openpyxl import Workbook 
wb = Workbook() 
wb.active =0 
ws = wb.active 
ws.title = "Repair" 
ws.sheet_properties.tabColor = "CCFFCC" 

print(wb.sheetnames) 

import datetime 
import smtplib 
import mimetypes 

import logging 
LOG_FILENAME = 'log-production.out' 
logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG) 

logging.debug('This message should go to the log file') 

from datetime import date, timedelta 
import os, sys 
try: 
    conn = psycopg2.connect("connection string") 
except: 
    print "I am unable to connect to the database" 

cur = conn.cursor() 
cur.execute("""SELECT ams.unit.line,ams.unit.work_order,ams.unit.model_num, ams.unit.revision ,ams.unit.serial_num,ams.unit.lpn, ams.unit_repair_detail.level_1_name as level_1, 
      ams.unit_repair_detail.level_2_name as level_2, ams.unit_repair_detail.level_3_name as level_3,ams.unit_repair_detail.level_4_name as level_4,ams.unit_repair.date_started AT TIME ZONE 'UTC' as date_started,ams.unit_repair.date_completed AT TIME ZONE 'UTC' as date_completed 
        FROM ams.unit_repair 
         left join 
          ams.unit 
            on ams.unit_repair.unit_id=ams.unit.id and 
            LOWER(ams.unit_repair.line) = LOWER(ams.unit.line) 
         right join 
          ams.unit_repair_detail 
            on ams.unit_repair.sid = ams.unit_repair_detail.unit_repair_sid 
            WHERE 
            LOWER(ams.unit.line) like ('%') and 
             ams.unit_repair_detail.date_created >= (CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - interval '24 hours') 
            AND ams.unit_repair_detail.date_created <= (CURRENT_TIMESTAMP AT TIME ZONE 'UTC') 
            and LOWER(ams.unit.model_num) like LOWER('%') 

            order by model_num asc""") 
rows = cur.fetchall() 
print "\nShow me the databases:\n" 
col_names = ["Line","Work order","Model number","Revision","Serial number","Lpn","Level 1","Level 2","Level 3","Level 4","Date started","Date completed"]  

ws.append(col_names) 
for row in rows: 
    ws.append(row) 

這是工作,但夏令時間後改變一切打破...查詢返回的分貝正確的數據,但是當我運行它從python腳本創建並且該文件仍處於UTC時間。我不知道我在做什麼,將我的日期轉換回UTC ...任何人都可以幫助我嗎?我試圖在頂部設置時區爲中心,使其與UTC轉換爲中心,沒有運氣

cur.execute("SET TIME ZONE 'America/Chicago';") 

我也曾嘗試

>>> import time 
>>> offset = time.timezone if (time.localtime().tm_isdst == 0) else time.altzone 
>>> offset/60/60 * -1 

我也試圖改變我的AT TIME ZONE UTC TO CST並沒有運氣......我在網上嘗試了多種解決方案,但似乎沒有任何工作。任何幫助將不勝感激!!

+0

與** openpyxl **無關,請刪除**標籤openpyxl **。 – stovfl

+0

你從命令行得到的結果是什麼?它們與Psycopg中的相同嗎? –

+0

以及我使用IDLE運行它,但我得到的結果就像我從查詢中的SELECT語句中刪除AT TIME ZONE'UTC'一樣。所以例如我得到的日期如:在我的xlsx文件上:2017-03-17 11:38:51當我運行查詢「2017-03-17 06:37:57.3-05」是你的意思是結果?我從來沒有得到任何錯誤...所以它運行良好,但日期是關閉它像轉換被忽略 – cocopan

回答

0

以防萬一有人跑進在未來這樣的事情...我發現這個問題,如果你添加以下到查詢

`at time zone 'America/Chicago' 

它會解決這個問題。不知何故at time zone UTC是不夠的,你仍然需要指定輸出時區