[英]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-dateutil
的tzlocal
時區來完成相同事情的另一種方法:
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
(我在AmbiguousTimeError
和ImaginaryTimeError
條件中添加了模擬pytz
接口。)請注意,我包含了這個,以防萬一你有類似的問題,由於某種原因需要參考本地時區 - 如果你有什么將以 UTC astimezone
為您提供正確答案,最好使用它,然后使用astimezone
將其放入您想要的任何本地區域。
這個怎么運作
由於您表示您對評論中的工作方式仍然有些困惑,因此我想我會澄清為什么會這樣。 有兩個函數可以將時間戳轉換為datetime.datetime
對象, datetime.datetime.fromtimestamp(timestamp, tz=None)
和datetime.datetime.utcfromtimestamp(timestamp)
:
utcfromtimestamp(timestamp)
會給你一個天真的datetime
時間,代表UTC時間。 然后,您可以執行dt.replace(tzinfo=pytz.utc)
(或任何其他utc
實現 - datetime.timezone.utc
、 dateutil.tz.tzutc()
等)來獲取日期時間並將其轉換為您的任何時區想。
fromtimestamp(timestamp, tz=None)
,當tz
不是None
,會給你一個相當於utcfromtimestamp(timestamp).replace(tzinfo=timezone.utc).astimezone(tz)
的感知datetime
utcfromtimestamp(timestamp).replace(tzinfo=timezone.utc).astimezone(tz)
。 如果tz
是None
,而不是將太多指定的時區,將其轉換為本地時間(相當於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.