0

I have the following datetime, and I converted to datetime object.

How do I convert it to say GMT+7 timezone?

date = "2020-07-27T16:38:20Z"

curr = datetime.strptime(date, "%Y-%m-%dT%H:%M:%S%z")
print(curr)
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • dupe, https://stackoverflow.com/q/10997577/4985099 – sushanth Jul 28 '20 at 03:36
  • 2
    Does this answer your question? [Python Timezone conversion](https://stackoverflow.com/questions/10997577/python-timezone-conversion) – Soumendra Jul 28 '20 at 04:20
  • Does this answer your question? [How do I parse an ISO 8601-formatted date?](https://stackoverflow.com/questions/127803/how-do-i-parse-an-iso-8601-formatted-date) – FObersteiner Jul 28 '20 at 05:59
  • related: https://stackoverflow.com/questions/63127525/python-convert-raw-gmt-to-othertime-zone-e-g-sgt (voted to close this question) – FObersteiner Jul 28 '20 at 06:15

2 Answers2

0

If converting to a timezone will work for you then you can convert it like this:

import datetime as dt
from pytz import timezone

date = "2020-07-27T16:38:20Z"

curr = (
    dt.datetime.strptime(date, "%Y-%m-%dT%H:%M:%S%z")
    .astimezone(timezone('US/Pacific'))
)
print(curr)

OUTPUT:
2020-07-27 09:38:20-07:00

You can list the available timezones like this:

from pytz import all_timezones

for tz in all_timezones:
    print(tz)
Trace Malloc
  • 394
  • 1
  • 3
  • 5
  • 1
    `pytz` is [to be deprecated](https://pypi.org/project/pytz-deprecation-shim/), use `dateutil` instead, or `zoneinfo` with Python 3.9. – FObersteiner Jul 28 '20 at 06:02
0

You can use this code here:

import pytz

date = datetime(2020, 7, 27, 16, 38, 20)
local_time_zone = pytz.timezone('GMT+0')

Or you can get your local time zone

# from tzlocal import get_localzone
# local_time_zone = get_localzone()


def utc_to_local(date):
    local_date = date.replace(tzinfo=pytz.utc).astimezone(local_time_zone)
    return local_time_zone.normalize(local_date)


print(utc_to_local(date).strftime('%Y-%m-%d %H:%M:%S.%f %Z%z'))
print(utc_to_local(datetime.utcnow()).strftime('%Y-%m-%d %H:%M:%S.%f %Z%z'))

The output will be like this:

2020-07-27 16:38:20.000000 GMT+0000
2020-07-28 13:31:23.219703 GMT+0000
Mahsa stz
  • 3
  • 2