繁体   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