我有一个变量,它保存的时间是 UTC 中的 datetime.time 类型,我希望它转换为其他时区。
我们可以转换 datetime.datetime 实例中的时区,如此链接所示 - 如何在 Python 中将本地时间转换为 UTC? .我无法弄清楚如何在 datetime.time 实例中转换时区。我不能使用 astimezone 因为 datetime.time 没有这个方法。
例如:
>>> t = d.datetime.now().time()
>>> t
datetime.time(12, 56, 44, 398402)
>>>
我需要 UTC 格式的“”。
原文由 rajpy 发布,翻译遵循 CC BY-SA 4.0 许可协议
有四种情况:
datetime.time
有tzinfo
设置(例如OP提到UTC)tzinfo
未设置)datetime.time
有tzinfo
未设置tzinfo
未设置)The correct answer needs to make use of
datetime.datetime.timetz()
function becausedatetime.time
cannot be built as a non-naive timestamp by callinglocalize()
orastimezone()
直接地。基于 OP 要求的示例:
如果需要天真的时间戳:
time() 实例已经
tzinfo
设置的情况更容易,因为datetime.combine
拾取tzinfo
我们只需要从传递的参数中进行转换,所以tz_out
。