作者guiltyboa (Crazy Ned)
看板Python
標題[問題] 存取DB datetimeoffset的問題
時間Wed Nov 20 10:37:07 2024
大家好
目前發現幾種存取資料庫 datetimeoffset欄位時,其內容會被轉換成 UTC+0
範例如下:
```
connection = get_connection()
cursor = connection.cursor()
# def utc+8 timezone
timezone_utc8 = pytz.timezone('Asia/Taipei')
utc8_time = datetime.now(timezone_utc8)
print(utc8_time)
query = """
INSERT INTO api_log (endpoint, method, request_body, response_body,
timestamp)
VALUES (?, ?, ?, ?, ? )
"""
cursor.execute(query, (
endpoint, method, request_body, response_body, utc8_time))
connection.commit()
cursor.close()
connection.close()
```
這個是一個 SQL Script commit的範例
其中 api_log timestamp的格式為 datetimeoffset
執行時可以看到 print(utc8_time) 的結果為 2024-11-20 10:24:43.115027+08:00
但在資料庫看到的卻會是 2024-11-20 10:24:43.1150270 +00:00
相同的狀況透過 Django ORM來實現
```
# 定義 UTC+8 時區
tz = pytz.timezone(settings.TIME_ZONE)
# get utc+8 time
current_utc_plus_8_time = timezone.now().astimezone(tz)
print("Current UTC+8 Time:", current_utc_plus_8_time)
# 紀錄 API 呼叫資訊到 ApiLog
ApiLog.objects.create(
endpoint=endpoint,
method=method,
request_body=request_body,
response_body=response_body,
timestamp=current_utc_plus_8_time # models.py 使用 DateTimeFeild()
)
```
其也會跟直接下 SQL commit一樣的結果
想問是否有方法可以確保寫入資料庫為正確的 UTC時區
另外 在測試這個欄位存取時也發現
我用Java 寫入的 UTC+8的內容
models.py 載入的資料會無視後面的 UTC+8,導致AP讀取時間會變成錯誤的時間。
https://imgur.com/mLJGLs6.png
https://imgur.com/zkOGFO9.png
--
◤ ◥ ◣▲◢ ◤≡.◥
蜘蛛人 ◣╳◢ 益rz ﹀▲﹀ 老人家 ═ ═
◣_ ◢▲ ◥皿 ◤▲ "︷\│▲
◤ ◤ ◤ ◤ ◤ ◤
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 27.242.194.70 (臺灣)
※ 文章網址: https://webptt.com/m.aspx?n=bbs/Python/M.1732070244.A.D27.html
1F:推 goitaly: 要不要把timestamp存成數字 取出來再轉成你要的時區時間 11/20 18:41
2F:→ goitaly: 就好?我自己是這樣處理 感覺比較直覺 11/20 18:41
3F:→ Hsins: 如果你這兩組程式,都是在 Django 下執行運作的話,要檢查 11/20 18:53
4F:→ Hsins: USE_TZ 和 TIME_ZONE。 11/20 18:53
5F:→ Hsins: 咦等等,你是直接存時間戳的話,對資料庫來說會預設會吃系 11/20 19:01
6F:→ Hsins: 統時區,所以你要去檢查跑 DB 服務的那台機器的時區設定 11/20 19:02
7F:→ Hsins: 如果可以,我會建議統一以 UTC 存時間,取出時再根據需要 11/20 19:07
8F:→ Hsins: 進行時間轉換。 11/20 19:07