Here I print UTC time zone's current datetime. I want current GMT time zone's datetime by this method. How can I?
import datetime
dt_utcnow = datetime.datetime.utcnow()
print(dt_utcnow)
Output
2020-08-31 09:06:26.661323
Here I print UTC time zone's current datetime. I want current GMT time zone's datetime by this method. How can I?
import datetime
dt_utcnow = datetime.datetime.utcnow()
print(dt_utcnow)
Output
2020-08-31 09:06:26.661323
You can use the gmtime() of time module to achieve this:
from datetime import datetime
from time import gmtime, strftime
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
print("Your Time Zone is GMT", strftime("%z", gmtime()))
At first, you need to import pytz module (you need to install it using CMD: pip install pytz
). Pytz library allows you to work with time zones.
To make code clear, we will save timezone into the variable GMT like this:
GMT = pytz.timezone("Etc/GMT")
If you want to now all possible timezones, you can just print out pytz.all_timezones
. Now, there are several ways how to solve your problem, but I will show you 2 of them:
Localize your UTC time into GMT: dt_gmt = GMT.localize(dt_utcnow)
Convert your time into GMT: dt_gmt = dt_utcnow.astimezone(gmt)