将Zulu时间字符串转换为MST日期时间对象 [英] Convert zulu time string to MST datetime object

查看:56
本文介绍了将Zulu时间字符串转换为MST日期时间对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将该字符串转换为MST时区 datetime 对象?

How can I convert this string to MST timezone datetime object?

>>> type(date_str)
<type 'str'>
>>> date_str
'2017-01-17T20:02:45.767Z'

推荐答案

这是 ISO 8601 兼容字符串.有许多可以转换的库.但是,要将其与时区转换结合使用,您可以:

This is an ISO 8601 compliant string. There are various libraries that can convert this. But to combine this with a Timezone conversion, you can:

import datetime as dt
from pytz import timezone

def convert_my_iso_8601(iso_8601, tz_info):
    assert iso_8601[-1] == 'Z'
    iso_8601 = iso_8601[:-1] + '000'
    iso_8601_dt = dt.datetime.strptime(iso_8601, '%Y-%m-%dT%H:%M:%S.%f')
    return iso_8601_dt.replace(tzinfo=timezone('UTC')).astimezone(tz_info)

my_dt = convert_my_iso_8601('2017-01-17T20:02:45.767Z', timezone('MST'))

这篇关于将Zulu时间字符串转换为MST日期时间对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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