Python时区转换会增加小时数吗? [英] Python timezone conversion adding minutes to the hour?

查看:85
本文介绍了Python时区转换会增加小时数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我试图将一小时(10:00:00、14:00:00等)从给定时区转换为UTC。

So I'm trying to convert a bunch of hours (10:00:00, 14:00:00, etc) from a given timezone to UTC.

这样做的时候,我会一直疯狂地回想起诸如 15:51:00之类的东西。

When I do so, I keep maddeningly getting things back like "15:51:00".

当您到达该行并打印其使用的值时,

When you get to that line, and print what value it's using, it's using something like:

1900-01-01 12:00:00-05:51

除了-05:51位之外,其他都可以。我不知道为什么有-05:51,这给我带来了麻烦。 UTC转换是小时到小时,是吗?我认为这与我的时区转换有关,但我真的不明白为什么他们会这样做。

Which is fine, except for the -05:51 bit. I have no idea why that -05:51 is there, and it's causing me problems. UTC conversion is hour to hour, yes? I think it's got something to do with my timezone conversions, but I really don't get why they would be doing that.

这是一个最小的例子,有同样的错误输出;它会返回 15:51:00 ,而应该只返回一个固定的小时,没有分钟。

Here's a minimal example that has the same erroneous output; it returns 15:51:00 when it should just return a flat hour, no minutes.

import datetime
from dateutil import tz

jj = datetime.datetime.strptime("10:00:00", "%H:%M:%S")

tzz = tz.gettz('US/Central')

def constructstring(tzz,x):
    inter2 = x.replace(tzinfo=tzz) #ERROR HAPPENS HERE (I'm pretty sure anyways)
    inter3 = inter2.astimezone(tz.tzutc())
    return inter3

print(constructstring(tzz,jj).strftime("%H:%M:%S"))


推荐答案

在创建 jj datetime对象时未指定日期,因此使用默认日期1900-01-01。时区不是固定的实体;它们会随时间变化,因此美国/中部时区在1900年使用了不同的偏移量。

You are not specifying a date when you create the jj datetime object, so the default date of 1900-01-01 is used. Timezones are not fixed entities; they change over time, and the US/Central timezone used a different offset back in 1900.

至少,请使用最近的日期,例如 today 例如:

At the very least, use a recent date, like today for example:

# use today's date, with the time from jj, and a given timezone.
datetime.datetime.combine(datetime.date.today(), jj.time(), tzinfo=tzz)

如果只需要一个时间,则不要创建 datetime 对象来存储它们; datetime 模块具有专用的 time()对象。我也不会使用 strftime()从文字中创建对象。只需使用构造函数来传递整数:

If all you need is a time, then don't create datetime objects to store those; the datetime module has a dedicated time() object. I'd also not use strftime() to create objects from literals. Just use the constructor to pass in integers:

jj = datetime.time(10, 0, 0)  # or just .time(10)

其他好的经验法则:如果必须处理带时区的日期,请尝试在代码接收或加载它们时,将它们移动到UTC中的 datetime 对象。如果您只有一天中的某个时间,但仍需要时区支持,请将它们附加到今天的日期,这样您就可以获得正确的时区。仅在尽可能晚的时候再次转换为字符串。

Other good rules of thumb: If you have to deal with dates with timezones, try to move those to datetime objects in UTC the moment your code receives or loads them. If you only have a time of day, but still need timezone support, attach them to today's date, so you get the right timezone. Only convert to strings again as late as possible.

这篇关于Python时区转换会增加小时数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆