Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

python - How to convert datetime.time from UTC to different timezone?

I have variable which holds time which is of type datetime.time in UTC, I wanted it to convert to some other timezone.

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.

For example:

>>> t = d.datetime.now().time()
>>> t
datetime.time(12, 56, 44, 398402)
>>> 

I need 't' in UTC format.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are four cases:

  1. input datetime.time has tzinfo set (eg OP mentions UTC)
    1. output as non-naive time
    2. output as naive time (tzinfo not set)
  2. input datetime.time has tzinfo not set
    1. output as non-naive time
    2. output as naive time (tzinfo not set)

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()

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)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...