nna*_*ski 4 python timezone pytz
我正在尝试制作一个带有时间对象并将其转换为UTC时间的函数.下面的代码似乎关闭了一个小时.当我通过转换器中午运行时,我回到18:00:00.但是当我通过在线转换器运行相同的数据时,我得到17:00:00.
我在这做错了什么?任何帮助将不胜感激.
import pytz, datetime
def convert_to_utc(time, tz):
now_dt = datetime.datetime.utcnow()
#get a date object
date_dt = now_dt.date()
#combine the current date object with our given time object
dt = datetime.datetime.combine(date_dt, time)
#get an timezone object for the source timezone
src_tz = pytz.timezone(str(tz))
#stamp the source datetime object with the src timezone
src_dt = dt.replace(tzinfo=src_tz)
#get the offset from utc to given timezone
offset = str(int(src_dt.strftime("%z"))).rstrip('0')
#convert the source datetime object to
utc_dt = src_dt.astimezone(pytz.utc)
#return the converted time and the offset in integer format
return (utc_dt.time(), int(offset))
time = datetime.datetime.strptime('12:00:00', "%H:%M:%S").time()
(TIME, offset) = convert_to_utc(time, 'America/Chicago')
print TIME.strftime("%H:%M:%S")
Run Code Online (Sandbox Code Playgroud)
**编辑**
这是更新的(和功能)代码,以防其他人需要帮助转换为/从UTC转换.
谢谢大家的帮助!
import pytz, datetime
def convert_to_utc(time, tz): #this returns the offset in int form as well
now_dt = datetime.datetime.utcnow()
#get a date object
date_dt = now_dt.date()
#combine the current date object with our given time object
dt = datetime.datetime.combine(date_dt, time)
#get an timezone object for the source timezone
src_tz = pytz.timezone(str(tz))
#stamp the source datetime object with the src timezone
src_dt = src_tz.localize(dt)
#get the offset from utc to given timezone
offset = str(int(src_dt.strftime("%z"))).rstrip('0')
#convert the source datetime object to
utc_dt = src_dt.astimezone(pytz.utc)
#return the converted time and the offset in integer format
return (utc_dt.time(), int(offset))
def convert_from_utc(time, tz):
now_dt = datetime.datetime.now()
date = now_dt.date()
dt = datetime.datetime.combine(date, time)
dest = pytz.timezone(str(tz))
dt = dt.replace(tzinfo=pytz.utc)
dest_dt = dt.astimezone(dest)
return dest_dt.time()
time = datetime.datetime.strptime('12:00:00', "%H:%M:%S").time()
(TIME, offset) = convert_to_utc(time, 'America/Chicago')
print TIME.strftime("%H:%M:%S")
utc_time = datetime.datetime.strptime('17:00:00', "%H:%M:%S").time()
TIME = convert_from_utc(utc_time, 'America/Chicago')
print TIME.strftime("%H:%M:%S")
Run Code Online (Sandbox Code Playgroud)
更改
src_dt = dt.replace(tzinfo=src_tz)
Run Code Online (Sandbox Code Playgroud)
至
src_dt = src_tz.localize(dt)
Run Code Online (Sandbox Code Playgroud)
使用localize夏令时调整,而replace不是.请参阅文档中标题为"本地化时间和日期算术" 的部分.