我正在尝试将具有特定时区(欧洲/巴黎)的时间戳转换为 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 来完成相同事情的另一种方法。的 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 接口(interface)。)请注意,我包括这个以防万一你有一个类似的问题,出于某种原因需要引用本地时区 - 如果你有一些东西可以在 UTC 中给你正确的答案,最好使用它然后使用 astimezone 来将它放入您想要的任何本地区域。
工作原理
既然你在评论中表示你对它的工作原理仍然有点困惑,我想我会澄清为什么它有效。有两个函数可以将时间戳转换为 datetime.datetime 对象,datetime.datetime.fromtimestamp(timestamp, tz=None)和 datetime.datetime.utcfromtimestamp(timestamp) :
utcfromtimestamp(timestamp)会给你一个 naivedatetime来表示 UTC 时间。然后您可以执行dt.replace(tzinfo=pytz.utc)(或任何其他utc实现 -datetime.timezone.utc,dateutil.tz.tzutc()等)以了解日期时间并将其转换为您想要的任何时区。fromtimestamp(timestamp, tz=None),当tz不是None时,会给你一个意识datetime等同于utcfromtimestamp(timestamp).replace(tzinfo=timezone.utc).astimezone(tz)。如果tz是None,它不会转换指定的时区,而是转换为您的本地时间(相当于dateutil.tz.tzlocal()),然后返回一个naivedatetime。
从 Python 3.6 开始,您可以使用 datetime.datetime.astimezone(tz=None)在 naive 日期时间上,时区将被假定为系统本地时间。因此,如果您正在开发 Python >= 3.6 应用程序或库,您可以使用 datetime.fromtimestamp(timestamp).astimezone(whatever_timezone) 或 datetime.utcfromtimestamp(timestamp).replace(tzinfo =timezone.utc).astimezone(whatever_timezone) 作为等价物。
