raj*_*jpy 9 python timezone datetime
我有变量,其中包含UTC时间类型为datetime.time的时间,我希望它转换为其他时区.
我们可以在datetime.datetime实例中转换时区,如此SO链接所示 - 如何在Python中将本地时间转换为UTC?.我无法弄清楚如何在datetime.time实例中转换时区.我不能使用astimezone,因为datetime.time没有这个方法.
例如:
>>> t = d.datetime.now().time()
>>> t
datetime.time(12, 56, 44, 398402)
>>>
Run Code Online (Sandbox Code Playgroud)
我需要UTC格式的't'.
小智 10
有四种情况:
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()
Run Code Online (Sandbox Code Playgroud)
基于 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>)
Run Code Online (Sandbox Code Playgroud)
如果需要朴素的时间戳:
time_to_tz_naive(t, pytz.utc, pytz.timezone('Europe/Berlin'))
datetime.time(14, 56, 44, 398402)
Run Code Online (Sandbox Code Playgroud)
其中时间()实例已经案件tzinfo设置更容易,因为datetime.combine拾取tzinfo从传递的参数,所以我们只需要转换为tz_out。
我会创建一个临时日期时间对象,转换tz,然后再次提取时间.
import datetime
def time_to_utc(t):
dt = datetime.datetime.combine(datetime.date.today(), t)
utc_dt = datetime_to_utc(dt)
return utc_dt.time()
t = datetime.datetime.now().time()
utc_t = time_to_utc(t)
Run Code Online (Sandbox Code Playgroud)
在哪里,datetime_to_utc是链接问题中的任何建议.