从本地时区转换为 utc 时区

发布于 2024-11-16 07:41:51 字数 2577 浏览 4 评论 0原文

我正在尝试创建一个函数,它接受一个时间对象并将其转换为 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")

**编辑**

这是更新的(和功能的)代码,以防其他人需要帮助转换为/来自 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")

I'm attempting to craft a function that takes a time object and converts it to UTC time. The code below appears to be off by one hour. When i run noon through the converter, i get back 18:00:00. But when i run the same data through online converters, i get 17:00:00.

What am i doing wrong here? Any help would be greatly appreciated.

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

**EDIT**

Here's the updated(and functional) code in case anyone else needs help converting to/from UTC.

Thanks everyone for your help!

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

与酒说心事 2024-11-23 07:41:51

更改

src_dt = dt.replace(tzinfo=src_tz)

src_dt = src_tz.localize(dt)

使用 localize 会针对夏令时进行调整,而 replace 则不会。
请参阅文档中标题为“本地化时间和日期算术”的部分

Change

src_dt = dt.replace(tzinfo=src_tz)

to

src_dt = src_tz.localize(dt)

Using localize adjusts for Daylight Savings Time, while replace does not.
See the section entitled "Localized times and date arithmetic" in the docs.

情丝乱 2024-11-23 07:41:51

要将给定时区的时间转换为 UTC 时间:

from datetime import datetime
import pytz

def convert_to_utc(time, tzname, date=None, is_dst=None):
    tz = pytz.timezone(tzname)
    if date is None: # use date from current local time in tz
        date = datetime.now(tz).date()

    dt = tz.localize(datetime.combine(date, time), is_dst=is_dst)
    return dt.astimezone(pytz.utc).time(), dt.utcoffset().total_seconds()

如果 is_dstNone,则会引发本地时间不明确的异常。

要将 UTC 时间转换为给定时区的本地时间:

def convert_from_utc(time, tzname, date=None):
    tz = pytz.timezone(tzname)
    if date is None: # use date from current time in utc
        date = datetime.utcnow().date()
    dt = datetime.combine(date, time).replace(tzinfo=pytz.utc)
    return tz.normalize(dt.astimezone(tz)).time()

示例:

time = datetime.strptime('12:00:00', "%H:%M:%S").time()
utc_time, offset = convert_to_utc(time, 'America/Chicago')
print utc_time.strftime("%H:%M:%S"), offset # -> 17:00:00 -18000.0

utc_time = datetime.strptime('17:00:00', "%H:%M:%S").time()
time = convert_from_utc(utc_time, 'America/Chicago')
print time.strftime("%H:%M:%S") # -> 12:00:00

一般来说,最好使用完整的 datetime 对象,以避免对正确日期产生歧义,即传递并返回 datetime< /代码> 对象。

To convert time in given timezone to UTC time:

from datetime import datetime
import pytz

def convert_to_utc(time, tzname, date=None, is_dst=None):
    tz = pytz.timezone(tzname)
    if date is None: # use date from current local time in tz
        date = datetime.now(tz).date()

    dt = tz.localize(datetime.combine(date, time), is_dst=is_dst)
    return dt.astimezone(pytz.utc).time(), dt.utcoffset().total_seconds()

if is_dst is None it raises an exception for ambiguous local times.

To convert UTC time to local time in given timezone:

def convert_from_utc(time, tzname, date=None):
    tz = pytz.timezone(tzname)
    if date is None: # use date from current time in utc
        date = datetime.utcnow().date()
    dt = datetime.combine(date, time).replace(tzinfo=pytz.utc)
    return tz.normalize(dt.astimezone(tz)).time()

Example:

time = datetime.strptime('12:00:00', "%H:%M:%S").time()
utc_time, offset = convert_to_utc(time, 'America/Chicago')
print utc_time.strftime("%H:%M:%S"), offset # -> 17:00:00 -18000.0

utc_time = datetime.strptime('17:00:00', "%H:%M:%S").time()
time = convert_from_utc(utc_time, 'America/Chicago')
print time.strftime("%H:%M:%S") # -> 12:00:00

In general it is preferable to work with full datetime objects to avoid ambiguity with what is the correct date i.e., pass and return datetime objects.

爱情眠于流年 2024-11-23 07:41:51

通过对日期时间使用 replace 方法,您将不允许根据夏令时调整时区。尝试使用 pytz 文档 中记录的方法之一:

src_dt = src_tz.localize(dt)

By using the replace method on the datetime, you're not allowing the time zone to be adjusted for daylight savings time. Try using one of the documented methods from the pytz documentation:

src_dt = src_tz.localize(dt)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文