![](/img/trans.png)
[英]Python - if given GMT Offset, and Given UTC - How to get the current time in a time zone?
[英]Get the GMT time given date and UTC offset in python
我有一个以下格式的日期字符串'%Y%m%d%H%M%S'
,例如'19981024103115'
和另一个UTC本地偏移字符串,例如'+0100'
将python转换为GMT时间的最佳方法是什么?
结果将是'1998-10-24 09:31:15'
您可以使用dateutil
:
>>> from dateutil.parser import parse
>>> dt = parse('19981024103115+0100')
>>> dt
datetime.datetime(1998, 10, 24, 10, 31, 15, tzinfo=tzoffset(None, 3600))
>>> dt.utctimetuple()
time.struct_time(tm_year=1998, tm_mon=10, tm_mday=24, tm_hour=9, tm_min=31, tm_sec=15, tm_wday=5, tm_yday=297, tm_isdst=0)
只要您知道时间偏移量始终为4位数形式,这应该可行。
def MakeTime(date_string, offset_string):
offset_hours = int(offset_string[0:3])
offset_minutes = int(offset_string[0] + offset_string[3:5])
gmt_adjust = datetime.timedelta(hours = offset_hours, minutes = offset_minutes)
gmt_time = datetime.datetime.strptime(date_string, '%Y%m%d%H%M%S') - gmt_adjust
return gmt_time
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.