1

I know this question has been asked in different forms, but I'm not finding what I need. I'm looking for a way to convert the following date / time to my local time zone using Python. Note the time zone of "Z" and the "T" between the date and time, this is what's throwing me off.

"startTime": "2021-03-01T21:21:00.652064Z"
martineau
  • 119,623
  • 25
  • 170
  • 301
Karl
  • 149
  • 3
  • 14
  • see e.g. [here](https://stackoverflow.com/q/62330675/10197418) how to go from UTC to local time and [here](https://en.wikipedia.org/wiki/ISO_8601) to get some background info on the format you have. – FObersteiner Mar 02 '21 at 09:22

2 Answers2

0

the datetime module is your friend. You seem to be dealing with a date-time stamp in ISO format. The datetime module has a class method to generate a datetime object from an ISO formatted string.

from datetime import datetime
dateinput = "2021-03-01T21:21:00.652064Z"
stamp = datetime.fromisoformat(dateinput)

But here you will get an error because the trailing 'Z' is not quite right. If you know that it's always going to be there, just lop off the last character. Otherwise you might have to do some string manipulation first.

stamp = datetime.fromisoformat(dateinput[:-1])

See also the strptime() class method to get datetime objects from arbitrarily formatted strings.

Hoping this helps...

Louis B.
  • 487
  • 1
  • 4
  • 8
0

datetime and pytz modules! Also depends on what you need, but below is the date and time object without the miliseconds part and a simple conversion to Berlin timezone.

import datetime
from pytz import timezone
berlin_timezone = pytz.timezone('Europe/Berlin')

your_time = datetime.datetime.strptime(startTime.split(".")[0], "%Y-%m-%dT%H:%M:%S")
your_time_utc = your_time.astimezone(berlin_timezone)
Tomasz
  • 19
  • 2
  • the OP's input specifies UTC (`Z`) - your answer doesn't take that into account and will give a wrong result. also, Python 3.9+ can handle time zones nicely by itself, see [zoneinfo](https://docs.python.org/3/library/zoneinfo.html). – FObersteiner Mar 02 '21 at 09:23