在Python中如何解析UTC偏移时区?

编程入门 行业动态 更新时间:2024-10-28 20:22:55
本文介绍了在Python中如何解析UTC偏移时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 假设我有一个时区,如2009-08-18 13:52:54-04。我可以使用这样的一行解析大部分:

datetime.strptime(time_string,%Y-%m-% d%H:%M:%S)

但是,我无法获取时区工作。有一个%Z处理文本时区(EST,UTC等),但我看不到任何可以解析-04的东西。

解决方案

我最近遇到同样的问题,并使用以下代码解决问题:

gmt_offset_str = time_string [-3:] gmt_offset_seconds = int(gmt_offset_str)* 60 * 60 timestamp = time.strptime(time_string [: - 4],'%Y-%m-%d%H:% M:%S') return time.localtime(time.mktime(timestamp)-gmt_offset_seconds)

我也会对更优雅的解决方案感兴趣。

Let's say I have a timezone like "2009-08-18 13:52:54-04". I can parse most of it using a line like this:

datetime.strptime(time_string, "%Y-%m-%d %H:%M:%S")

However, I can't get the timezone to work. There's a %Z that handles textual timezones ("EST", "UTC", etc) but I don't see anything that can parse "-04".

解决方案

I ran across the same issue recently and worked around it using this code:

gmt_offset_str = time_string[-3:] gmt_offset_seconds = int(gmt_offset_str)*60*60 timestamp = time.strptime(time_string[:-4], '%Y-%m-%d %H:%M:%S') return time.localtime(time.mktime(timestamp)-gmt_offset_seconds)

I would also be interested in a more elegant solution.

更多推荐

在Python中如何解析UTC偏移时区?

本文发布于:2023-10-24 10:00:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1523650.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时区   Python   UTC

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!