Python将具有特定时区的时间戳转换为UTC中的日期时间

Mat*_*att 4 python datetime pytz

我正在尝试将具有特定时区(欧洲/巴黎)的时间戳转换为 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)
Run Code Online (Sandbox Code Playgroud)

谢谢

Pau*_*aul 5

我不确定是什么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)
Run Code Online (Sandbox Code Playgroud)

为了完整起见,这是通过引用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
Run Code Online (Sandbox Code Playgroud)

(我添加了AmbiguousTimeErrorImaginaryTimeError条件来模拟pytz界面。)请注意,我包含这个只是为了防止您遇到类似的问题,出于某种原因需要参考本地时区 - 如果您有一些东西可以给您UTC 中的正确答案,最好使用它,然后astimezone将其放入您想要的任何本地区域。

这个怎么运作

由于您表示您对评论中的工作方式仍然有些困惑,因此我想我会澄清为什么会这样。有两个函数可以将时间戳转换为datetime.datetime对象,datetime.datetime.fromtimestamp(timestamp, tz=None)并且datetime.datetime.utcfromtimestamp(timestamp)

  1. utcfromtimestamp(timestamp)会给你一个代表UTC时间的天真 datetime。然后,您可以执行dt.replace(tzinfo=pytz.utc)(或任何其他utc实现 - datetime.timezone.utcdateutil.tz.tzutc()等)来获取日期时间并将其转换为您想要的任何时区。

  2. fromtimestamp(timestamp, tz=None),当tz不是None,会给你一个意识 datetime相当于utcfromtimestamp(timestamp).replace(tzinfo=timezone.utc).astimezone(tz)。如果tzNone,它不会转换指定的时区,而是转换为您的本地时间(相当于dateutil.tz.tzlocal()),然后返回一个naive 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)作为等效项。