将祖鲁时间字符串转换为 MST 日期时间对象
Convert zulu time string to MST datetime object
如何将此字符串转换为 MST 时区 datetime
对象?
>>> type(date_str)
<type 'str'>
>>> date_str
'2017-01-17T20:02:45.767Z'
这是一个ISO 8601 compliant string. There are various libraries that can convert。但要将其与时区转换相结合,您可以:
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'))
这里有一个 Python 3.9 选项,仅使用标准库:
from datetime import datetime
from zoneinfo import ZoneInfo
date_str = '2017-01-17T20:02:45.767Z'
# to datetime, UTC:
dt = datetime.fromisoformat(date_str.replace('Z', '+00:00'))
# to mountain standard time:
dt_mountain = dt.astimezone(ZoneInfo("America/Denver"))
print(dt_mountain.isoformat())
# 2017-01-17T13:02:45.767000-07:00
对于旧版本,使用 dateutil 的不同方法:
from datetime import datetime
import dateutil
date_str = '2017-01-17T20:02:45.767Z'
# to datetime, UTC:
dt = dateutil.parser.parse(date_str)
# to mountain standard time:
dt_mountain = dt.astimezone(dateutil.tz.gettz("America/Denver"))
print(dt_mountain.isoformat())
# 2017-01-17T13:02:45.767000-07:00
如何将此字符串转换为 MST 时区 datetime
对象?
>>> type(date_str)
<type 'str'>
>>> date_str
'2017-01-17T20:02:45.767Z'
这是一个ISO 8601 compliant string. There are various libraries that can convert。但要将其与时区转换相结合,您可以:
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'))
这里有一个 Python 3.9 选项,仅使用标准库:
from datetime import datetime
from zoneinfo import ZoneInfo
date_str = '2017-01-17T20:02:45.767Z'
# to datetime, UTC:
dt = datetime.fromisoformat(date_str.replace('Z', '+00:00'))
# to mountain standard time:
dt_mountain = dt.astimezone(ZoneInfo("America/Denver"))
print(dt_mountain.isoformat())
# 2017-01-17T13:02:45.767000-07:00
对于旧版本,使用 dateutil 的不同方法:
from datetime import datetime
import dateutil
date_str = '2017-01-17T20:02:45.767Z'
# to datetime, UTC:
dt = dateutil.parser.parse(date_str)
# to mountain standard time:
dt_mountain = dt.astimezone(dateutil.tz.gettz("America/Denver"))
print(dt_mountain.isoformat())
# 2017-01-17T13:02:45.767000-07:00