3

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

>>> type(date_str)
<type 'str'>
>>> date_str
'2017-01-17T20:02:45.767Z'
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
rodee
  • 3,233
  • 5
  • 34
  • 70

2 Answers2

3

Here's a Python 3.9 option, using the standard lib only:

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

For older versions, a different approach using 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
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
1

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'))
Community
  • 1
  • 1
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
  • Is there a way to take day light savings time into account? the above code doesn't – rodee Mar 29 '17 at 20:31
  • Doesn't take DST into account how? The Z implies the original timestamp is in Zulu. Thus it does not have DST. Thus I think the only thing you should need to do for DST is apply a timezone which has one. I used MST only since you had. What timezone did you have in mind? – Stephen Rauch Mar 29 '17 at 20:45
  • The input I get is still zulu time, I would like to convert it to MST with DST accounted. – rodee Mar 30 '17 at 14:34
  • There at least three different time zones that are abbreviated as MST. http://www.timeandzone.com/zones-abbreviation?hl=en – Stephen Rauch Mar 30 '17 at 15:50
  • Forgive me, now I understand, it's `Mountain Standard (North America)` – rodee Mar 30 '17 at 16:21