簡體   English   中英

Python將具有特定時區的時間戳轉換為UTC中的日期時間

[英]Python convert timestamps with specific timezone to datetime in UTC

我正在嘗試將具有特定時區(歐洲/巴黎)的時間戳轉換為 UTC 中的日期時間格式。 在我的筆記本電腦上,它適用於下面的解決方案,但是當我在遠程服務器(愛爾蘭的 AWS-Lambda 函數)中執行我的代碼時,我有 1 小時的班次,因為服務器的本地時區與我的不同。 我怎樣才能有一個可以在我的筆記本電腦上同時在遠程服務器上工作的代碼(動態處理本地時區)?

import pytz
import datetime

def convert_timestamp_in_datetime_utc(timestamp_received):
    utc = pytz.timezone('UTC')
    now_in_utc = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(pytz.UTC)
    fr = pytz.timezone('Europe/Paris')
    new_date = datetime.datetime.fromtimestamp(timestamp_received)
    return fr.localize(new_date, is_dst=None).astimezone(pytz.UTC)

謝謝

我不確定什么是timestamp_received ,但我認為你想要的是utcfromtimestamp()

import pytz
from datetime import datetime

def convert_timestamp_in_datetime_utc(timestamp_received):
    dt_naive_utc = datetime.utcfromtimestamp(timestamp_received)
    return dt_naive_utc.replace(tzinfo=pytz.utc)

為了完整python-dateutil ,這是通過引用python-dateutiltzlocal時區來完成相同事情的另一種方法:

from dateutil import tz
from datetime import datetime
def convert_timestamp_in_datetime_utc(timestamp_received):
    dt_local = datetime.fromtimestamp(timestamp_received, tz.tzlocal())

    if tz.datetime_ambiguous(dt_local):
        raise AmbiguousTimeError

    if tz.datetime_imaginary(dt_local):
        raise ImaginaryTimeError

    return dt_local.astimezone(tz.tzutc())


class AmbiguousTimeError(ValueError):
    pass

class ImaginaryTimeError(ValueError):
    pass

(我在AmbiguousTimeErrorImaginaryTimeError條件中添加了模擬pytz接口。)請注意,我包含了這個,以防萬一你有類似的問題,由於某種原因需要參考本地時區 - 如果你有什么將以 UTC astimezone為您提供正確答案,最好使用它,然后使用astimezone將其放入您想要的任何本地區域。

這個怎么運作

由於您表示您對評論中的工作方式仍然有些困惑,因此我想我會澄清為什么會這樣。 有兩個函數可以將時間戳轉換為datetime.datetime對象, datetime.datetime.fromtimestamp(timestamp, tz=None)datetime.datetime.utcfromtimestamp(timestamp)

  1. utcfromtimestamp(timestamp)會給你一個天真的datetime時間,代表UTC時間。 然后,您可以執行dt.replace(tzinfo=pytz.utc) (或任何其他utc實現 - datetime.timezone.utcdateutil.tz.tzutc()等)來獲取日期時間並將其轉換為您的任何時區想。

  2. fromtimestamp(timestamp, tz=None) ,當tz不是None ,會給你一個相當於utcfromtimestamp(timestamp).replace(tzinfo=timezone.utc).astimezone(tz)感知datetime utcfromtimestamp(timestamp).replace(tzinfo=timezone.utc).astimezone(tz) 如果tzNone ,而不是將太多指定的時區,將其轉換為本地時間(相當於dateutil.tz.tzlocal()然后返回一個天真的datetime

從 Python 3.6 開始,您可以在原始日期時間上使用datetime.datetime.astimezone(tz=None) ,並且時區將被假定為系統本地時間。 因此,如果您正在開發 Python >= 3.6 應用程序或庫,則可以使用datetime.fromtimestamp(timestamp).astimezone(whatever_timezone)datetime.utcfromtimestamp(timestamp).replace(tzinfo=timezone.utc).astimezone(whatever_timezone)作為等價物。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM