当我有 UTC 偏移量时如何创建 tzinfo? [英] How to create tzinfo when I have UTC offset?

查看:65
本文介绍了当我有 UTC 偏移量时如何创建 tzinfo?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个时区与 UTC 的偏移量(以秒为单位)(19800),并且还有字符串格式 - +0530.

如何使用它们来创建 tzinfo 实例?我查看了 pytz,但在那里我只能找到以时区名称作为输入的 API.

解决方案

如果可以,看看优秀的 dateutil打包而不是自己实现.

具体来说,tzoffset.这是一个固定偏移量 tzinfo 实例,用 offset 初始化,以秒为单位,这就是你要找的.

更新

这是一个例子.请务必先运行 pip install python-dateutil.

from datetime import datetime从 dateutil 导入 tz# 首先创建tzinfo对象tzlocal = tz.tzoffset('IST', 19800)# 现在将它添加到一个简单的日期时间本地 = naive.replace(tzinfo=tzlocal)# 或者将另一个时区转换为它utcnow = datetime.utcnow().replace(tzinfo=tz.tzutc())现在 = utcnow.astimezone(tzlocal)

我从这里查找名称 IST .这个名字真的可以是任何东西.如果你偏离了,请小心,因为如果你使用依赖于名称的代码,它可能会在以后导致错误.

顺便说一句,如果您预先有时区名称,并且您的操作系统支持它,您可以使用 gettz 代替:

# 把上面的替换成这个tzlocal = tz.gettz('IST')

I have one timezone's offset from UTC in seconds (19800) and also have it in string format - +0530.

How do I use them to create a tzinfo instance? I looked into pytz, but there I could only find APIs that take timezone name as input.

解决方案

If you can, take a look at the excellent dateutil package instead of implementing this yourself.

Specifically, tzoffset. It's a fixed offset tzinfo instance initialized with offset, given in seconds, which is what you're looking for.

Update

Here's an example. Be sure to run pip install python-dateutil first.

from datetime import datetime
from dateutil import tz

# First create the tzinfo object
tzlocal = tz.tzoffset('IST', 19800)

# Now add it to a naive datetime
local = naive.replace(tzinfo=tzlocal)

# Or convert another timezone to it
utcnow = datetime.utcnow().replace(tzinfo=tz.tzutc())
now = utcnow.astimezone(tzlocal)

I looked up the name IST from here. The name can really be anything. Just be careful if you deviate, since if you use code that relies on the name, it could lead to bugs later on.

By the way, if you have the timezone name upfront, and your operating system supports it, you can use gettz instead:

# Replace the above with this
tzlocal = tz.gettz('IST')

这篇关于当我有 UTC 偏移量时如何创建 tzinfo?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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