pytz - 将 UTC 和时区转换为本地时间 [英] pytz - Converting UTC and timezone to local time

查看:79
本文介绍了pytz - 将 UTC 和时区转换为本地时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 UTC 时区有一个 datetime,例如:

I have a datetime in utc time zone, for example:

utc_time = datetime.datetime.utcnow()

还有一个 pytz 时区对象:

And a pytz timezone object:

tz = timezone('America/St_Johns')

utc_time 转换为给定时区的正确方法是什么?

What is the proper way to convert utc_time to the given timezone?

推荐答案

我想我明白了:

pytz.utc.localize(utc_time, is_dst=None).astimezone(tz)

这一行首先将原始(不知道时区)utc_time datetime 对象转换为包含时区 (UTC) 的 datetime 对象.然后它使用 astimezone 根据请求的时区调整时间的功能.

This line first converts the naive (time zone unaware) utc_time datetime object to a datetime object that contains a timezone (UTC). Then it uses the astimezone function to adjust the time according to the requested time zone.

这篇关于pytz - 将 UTC 和时区转换为本地时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆