0

I have an API that return this date string

strdate = '2019-10-07T06:09:28.984Z'

How do I convert it to a datetime object?

dt = datetime.datetime.strptime(strdate, '%Y-%m-%d')

If I use strptime like above i get "ValueError: unconverted data remains: T06:09:54.346Z" What do I do if there is "T" and "Z" included in the string date? I want the data in local time. But is the string really timezone aware so I can convert it properly? In this case I know the timezone, but what if I did not know?

geogrow
  • 485
  • 2
  • 9
  • 26
  • 2
    Possible duplicate of [Convert UTC datetime string to local datetime](https://stackoverflow.com/questions/4770297/convert-utc-datetime-string-to-local-datetime) – sahasrara62 Oct 07 '19 at 06:18

2 Answers2

1

The error is because you're not including the time part in the format string. Do that:

datetime.strptime('2019-10-07T06:09:28.984Z', '%Y-%m-%dT%H:%M:%S.%f%z')

This results in:

datetime.datetime(2019, 10, 7, 6, 9, 28, 984000, tzinfo=datetime.timezone.utc)

If you want to convert this to a local timezone, do that:

from pytz import timezone

dt = datetime.strptime(strdate, '%Y-%m-%dT%H:%M:%S.%f%z')
local_dt = dt.astimezone(timezone('Asia/Tokyo'))

Demo: https://repl.it/repls/RotatingSqueakyCertifications

deceze
  • 510,633
  • 85
  • 743
  • 889
1
import datetime
strdate = '2019-10-07T06:09:28.984Z'
dt=datetime.datetime.strptime(strdate, "%Y-%m-%dT%H:%M:%S.%fZ")
print(dt)

# output - 2019-10-07 06:09:28.984000
sameer_nubia
  • 721
  • 8
  • 8