有四种情况:
- 输入
datetime.time已tzinfo设置(例如 OP 提到 UTC)
- 输出为非天真时间
- 输出为幼稚时间(
tzinfo未设置)
- 输入未
datetime.time设置tzinfo
- 输出为非天真时间
- 输出为幼稚时间(
tzinfo未设置)
正确答案需要使用datetime.datetime.timetz()函数,因为不能通过调用或直接datetime.time构建为非天真的时间戳。localize()astimezone()
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 要求的示例:
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>)
如果需要简单的时间戳:
time_to_tz_naive(t, pytz.utc, pytz.timezone('Europe/Berlin'))
datetime.time(14, 56, 44, 398402)
time() 实例已经tzinfo设置的情况更容易,因为从传递的参数中datetime.combine获取tzinfo,所以我们只需要转换为tz_out.