5

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
  • Does this answer your question? [How to convert datetime.time from UTC to different timezone?](https://stackoverflow.com/questions/16603645/how-to-convert-datetime-time-from-utc-to-different-timezone) – The Pjot Aug 31 '20 at 09:23
  • 1
    **UTC** is **GMT** :-) –  Aug 31 '20 at 09:28
  • `from datetime import datetime, timezone` `utc_time = datetime.now(timezone.utc)` – Kebman Jul 30 '21 at 19:38
  • GMT and UTC are within a second of each other but they are not the same. If you need accuracy within 1 second then they are not interchangeably. – Gregology Sep 26 '21 at 14:08

2 Answers2

5

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()))
Seyi Daniel
  • 2,259
  • 2
  • 8
  • 18
0

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:

  1. Localize your UTC time into GMT: dt_gmt = GMT.localize(dt_utcnow)

  2. Convert your time into GMT: dt_gmt = dt_utcnow.astimezone(gmt)

vlado_sl
  • 75
  • 1
  • 1
  • 7
  • Thanks brother. But when I try to install pytz by pip "pip install pytz". But it shows that "Requirement already satisfied: pytz in c:\users\jjj\anaconda3\lib\site-packages". What is the solution? –  Aug 31 '20 at 10:00
  • It's alright. It just says that you have already installed this library. c:\users\... is just location of the library on your PC. – vlado_sl Aug 31 '20 at 10:10
  • But I can't import it. HOw can I? –  Sep 02 '20 at 01:42