在Python中如何解析UTC偏移时区? [英] How do I parse timezones with UTC offsets in Python?

查看:322
本文介绍了在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偏移时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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