Python change Datetime Timezone

Convert timezone using pytz package. Here’s how to install it

pip install pytz

Python datetime set time zone

Change the current time to UTC time zone.

from pytz import timezone
from datetime import datetime

f = "%Y-%m-%d %H:%M:%S %Z%z"

now_timezone = datetime.now(timezone('UTC'))
print (now_timezone.strftime(f))

Result >> 2020-11-19 10:46:02 UTC+0000

Add timezone on a string date

from pytz import timezone
from datetime import datetime

f = "%Y-%m-%d %H:%M:%S %Z%z"

str_date = "2020-11-19 14:18:01"
date_obj = datetime.strptime(str_date, "%Y-%m-%d %H:%M:%S")
date_obj_utc = date_obj.replace(tzinfo=timezone('UTC'))
print(date_obj_utc.strftime(f))

Result >> 2020-11-19 14:18:01 UTC+0000

Convert datetime to different format. This format usually used on TV EPG guide xml file.


str_date = "20201120173000 +0000"
date_obj = datetime.strptime(str_date, "%Y%m%d%H%M%S %z")
print(date_obj.strftime(f))

Result >> 2020-11-20 17:30:00 UTC+0000

Python datetime change time zone to US/Eastern


date_eastern = date_obj.astimezone(timezone('US/Eastern'))
print (date_eastern.strftime(f))

Result >> 2020-11-20 12:30:00 EST-0500

Python list timezone

List Asia time zone

from pytz import all_timezones
for zone in all_timezones:
    if 'Asia' in zone:
        print (zone)

List US time zone

from pytz import all_timezones
for zone in all_timezones:
    if 'US' in zone:
        print (zone)

List Europe time zone

from pytz import all_timezones
for zone in all_timezones:
    if 'Europe' in zone:
        print (zone)

Fixing errors:

ModuleNotFoundError: No module named ‘pytz’

pip install pytz

Leave a Comment

Your email address will not be published.