How to convert datetime.time from UTC to different timezone?(如何将 datetime.time 从 UTC 转换为不同的时区?)
问题描述
我有一个保存时间的变量,它是 UTC 中的 datetime.time 类型,我希望它转换为其他时区.
I have variable which holds time which is of type datetime.time in UTC, I wanted it to convert to some other timezone.
我们可以转换 datetime.datetime 实例中的时区,如此链接所示 - 如何在 Python 中将本地时间转换为 UTC?.我无法弄清楚如何在 datetime.time 实例中转换时区.我不能使用 astimezone 因为 datetime.time 没有这个方法.
we can convert timezones in datetime.datetime instance as shown in this SO link - How do I convert local time to UTC in Python?. I am not able to figure out how to convert timezones in datetime.time instances. I can't use astimezone because datetime.time doesn't have this method.
例如:
>>> t = d.datetime.now().time()
>>> t
datetime.time(12, 56, 44, 398402)
>>>
我需要 UTC 格式的t".
I need 't' in UTC format.
推荐答案
有四种情况:
- input
datetime.time设置了tzinfo(例如 OP 提到 UTC)
- input
datetime.timehastzinfoset (eg OP mentions UTC)
- 输出为非天真的时间
- 作为原始时间输出(
tzinfo未设置)
datetime.time 未设置 tzinfo
- 输出为非天真的时间
- 作为原始时间输出(
tzinfo未设置)
正确答案需要使用 datetime.datetime.timetz() 函数,因为 datetime.time 不能通过调用 构建为非朴素时间戳>localize() 或 astimezone() 直接.
The correct answer needs to make use of datetime.datetime.timetz() function because datetime.time cannot be built as a non-naive timestamp by calling localize() or astimezone() directly.
from datetime import datetime, time
import pytz
def timetz_to_tz(t, tz_out):
return datetime.combine(datetime.today(), t).astimezone(tz_out).timetz()
def timetz_to_tz_naive(t, tz_out):
return datetime.combine(datetime.today(), t).astimezone(tz_out).time()
def time_to_tz(t, tz_out):
return tz_out.localize(datetime.combine(datetime.today(), t)).timetz()
def time_to_tz_naive(t, tz_in, tz_out):
return tz_in.localize(datetime.combine(datetime.today(), t)).astimezone(tz_out).time()
基于 OP 要求的示例:
Example based on OP requirement:
t = time(12, 56, 44, 398402)
time_to_tz(t, pytz.utc) # assigning tzinfo= directly would not work correctly with other timezones
datetime.time(12, 56, 44, 398402, tzinfo=<UTC>)
如果需要简单的时间戳:
In case naive timestamp is wanted:
time_to_tz_naive(t, pytz.utc, pytz.timezone('Europe/Berlin'))
datetime.time(14, 56, 44, 398402)
time() 实例已经 tzinfo 设置的情况更容易,因为 datetime.combine 从传递的参数中提取 tzinfo, 所以我们只需要转换成 tz_out.
The cases where the time() instance has already tzinfo set are easier because datetime.combine picks up the tzinfo from the passed parameter, so we just need to convert to tz_out.
这篇关于如何将 datetime.time 从 UTC 转换为不同的时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将 datetime.time 从 UTC 转换为不同的时区?
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
