有四种情况:
- 输入
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。